httpcomponents-core-4.3.2/0040755 0000000 0000000 00000000000 12276757360 014304 5ustar000000000 0000000 httpcomponents-core-4.3.2/RELEASE_NOTES.txt0100644 0000000 0000000 00000153104 12276755416 017076 0ustar000000000 0000000 Release 4.3.2 ------------------- This maintenance release fixes a number of bugs and regressions found since 4.3.1, mostly in the NIO transport components. All users of HttpCore 4.3 are advised to upgrade. Changelog ------------------- * [HTTPCORE-371] Support for SSL re-negotiation with NIO. Contributed by Asankha Perera * [HTTPCORE-373] Out of sequence HTTP response causes NPE in HttpAsyncRequestExecutor. Contributed by Oleg Kalnichevski * [HTTPCORE-370] Race condition if connection request succeeds and times out at the same time. Contributed by Oleg Kalnichevski * (Regression) Fixed synchronization issue in blocking and non-blocking connection pool implementations caused by HTTPCORE-362 Contributed by Oleg Kalnichevski Release 4.3.1 ------------------- This maintenance release fixes a number of bugs and regressions found since 4.3, mostly in the NIO transport components. All users of HttpCore 4.3 are advised to upgrade. Changelog ------------------- * [HTTPCORE-367] (Regression) Non-blocking connections can enter a tight loop while waiting for a chunk header split across multiple TCP frames. Contributed by Oleg Kalnichevski * [HTTPCORE-366] Non-blocking SSLIOSession can enter an infinite loop if the underlying channel receives incoming data simultaneously with inactivity timeout. Contributed by Oleg Kalnichevski * [HTTPCORE-364] IOSessionImpl.getLocalAddress() (etc.) creates unnecessary copy of channel * DefaultConnectingIOReactor / DefaultListeningIOReactor do not correctly apply some initial socket settings. Contributed by Andreas Veithen * [HTTPCORE-357] Avoid DNS lookups in SSLIOSessions in server mode. Contributed by Isaac Cruz Ballesteros * [HTTPCORE-362] Purge pool per route map after closing out expired or idle connections with #closeExpired and #closeIdle methods. Contributed by Oleg Kalnichevski * [HTTPCORE-361] Reduced intermediate garbage in HeaderGroup#getFirstHeader() Contributed by Oleg Kalnichevski * [HTTPCORE-355] HttpAsyncRequestExecutor fails when its handler is not ready to generate a request. Contributed by jd * [HTTPCORE-354] BasicConnFactory don't use SocketConfig#isSoKeepAlive. Contributed by David Ignjic * [HTTPCORE-347] (Regression) HttpResponse#setStatusCode() does not update reason phrase. Contributed by Oleg Kalnichevski Release 4.3 ------------------- This is the first stable (GA) release of HttpCore 4.3. The most notable features in the 4.3 branch are: * Deprecation of preference and configuration API based on HttpParams interface in favor of constructor injection and plain configuration objects. * Reliance on object immutability instead of access synchronization for thread safety. Several old classes whose instances can be shared by multiple request exchanges have been replaced by immutable equivalents. The 4.3 branch also contains performance optimizations such as reduced TCP packet fragmentation and more efficient lease / release operations for pools of persistent connections on the client side. This release also includes all fixes from the 4.2.x release branch. Users of HttpCore 4.2 are encouraged to upgrade. Changelog ------------------- * [HTTPCORE-343] AbstractNIOConnPool to fire request callbacks outside the pool lock. This makes it possible to re-enter pool methods from a callback event. Contributed by Oleg Kalnichevski * [HTTPCORE-340] AbstractNIOConnPool to support lease timeout distinct from connect timeout. Contributed by Ignat Alexeyenko * Blocking connections do not clean session input buffer when closed (input data from a read operation may still remain in the buffer if the connection is re-opened). Contributed by Oleg Kalnichevski Release 4.2.5 ------------------- This maintenance release fixes a number of bugs found in NIO components since 4.2.4. We advise users of HttpCore NIO of all versions to upgrade. This is likely to be the last release in the 4.2.x branch. Changelog ------------------- * [HTTPCORE-345] EntityAsyncContentProducer fails to release resources allocated by the underlying entity when #produceContent is never invoked. Contributed by Tad Whitenight * Non-blocking connection pool to avoid scanning the entire queue of pending connection requests on each connection lease / release operation (under heavy load the request queue can contain a significant number of pending requests, a full linear scan of which can cause massive performance degradation). Contributed by Oleg Kalnichevski * Use bulk ByteBuffer#put method instead of single byte ByteBuffer#put Contributed by Oleg Kalnichevski * [HTTPCORE-336] Unhandled CancelledKeyException leads to a shutdown of the underlying IOReactor. Contributed by Thomas Dudek Release 4.3-BETA2 ------------------- This is the second BETA release from the 4.3.x release branch. This release addresses performance issues in the non-blocking connection pool implementation and also includes a number of performance improvements in the low level NIO based transport components. Changelog ------------------- * [HTTPCORE-300] ContentType to provide support for custom parameters. Contributed by Oleg Kalnichevski * Non-blocking connection pool to avoid scanning the entire queue of pending connection requests on each connection lease / release operation (under heavy load the request queue can contain a significant number of pending requests, a full linear scan of which can cause massive performance degradation). Contributed by Oleg Kalnichevski * Basic connection pool implementations to perform default port resolution for HTTP and HTTPS schemes. Contributed by Oleg Kalnichevski * Use bulk ByteBuffer#put method instead of single byte ByteBuffer#put Contributed by Oleg Kalnichevski * [HTTPCORE-336] Unhandled CancelledKeyException leads to a shutdown of the underlying IOReactor. Contributed by Thomas Dudek Release 4.3-BETA1 ------------------- This is the first BETA release from the 4.3.x release branch. The main theme of the 4.3 release series is streamlining of component configuration and deprecation of the old configuration API based on HttpParams in favor of constructor-based dependency injection and plain objects for configuration parameters. This release also includes performance optimizations intended to reduce TCP packet fragmentation when writing out HTTP messages both in blocking and non-blocking I/O modes, which should result in up to 20% higher throughput for short entity enclosing messages. This release also includes all fixes from the stable 4.2.x release branch. Changelog ------------------- * Reduced TCP packet fragmentation when writing out message content with blocking and non-blocking connections. Contributed by Oleg Kalnichevski * [HTTPCORE-330] Clarify InputStreamEntity length constructor argument. Contributed by John McCarthy * [HTTPCORE-323] Undocumented UnsupportedCharsetException in ContentType#getOrDefault. Contributed by Gary D. Gregory Release 4.2.4 ------------------- This maintenance release fixes a number of bugs found in NIO components since 4.2.3. We advise users of HttpCore NIO of all versions to upgrade. Changelog ------------------- * [HTTPCORE-334] https request to a non-responsive but alive port over a non-blocking connection results in a busy loop in one of I/O dispatch threads. Contributed by Scott Stanton * [HTTPCORE-331] BasicFuture no longer executes notification callbacks inside a synchronized block. Contributed by Oleg Kalnichevski * [HTTPCORE-319] Non-blocking SSLIOSession can fail to shut down correctly when the underlying connection gets terminated abnormally by the opposite endpoint in case there is a truncated or corrupted encrypted content in the input buffer and there is still data in the output buffer that needs to be flushed out (most likely to occur with POST or PUT requests). Contributed by Oleg Kalnichevski Release 4.1-ALPHA1 ------------------- This is the first release from the 4.3.x release branch. The main focus of the 4.3 release series is streamlining of component configuration and deprecation of the old configuration API based on HttpParams in favor of constructor based dependency injection and plain objects for configuration parameters. We are kindly asking all upstream projects to review API changes and help us improve the APIs by providing feedback and sharing ideas on dev@hc.apache.org. This release also includes all fixes from the stable 4.2.x release branch. Release 4.2.3 ------------------- This maintenance release fixes a number of bugs and found since 4.2.2 including a major bug in the NIO module that can cause an infinite loop in SSL sessions under special circumstances when the remote peer terminates the session in the middle of SSL handshake. Please note this issue does not affect blocking I/O components used by HttpClient. We advise users of HttpCore NIO of all versions to upgrade. Changelog ------------------- * [HTTPCORE-319, HTTPCORE-322] Non-blocking SSLIOSession can enter an infinite loop under special circumstances when the remote peer terminates the session in the middle of SSL handshake. Contributed by Paul Donohue and Oleg Kalnichevski * [HTTPCORE-316] HeaderGroup#clone removes headers from the original object. Contributed by Markus Thies * [HTTPCORE-315] AbstractNIOConnPool fails to correctly deallocate connection if it is immediately released from the session request callback causing a resource leak. Contributed by Scott Stanton * [HTTPCORE-313] ContentType#parse now ignores empty and blank charset attributes. HttpEntityUtils#toString now throws checked I/O exception if it encounters an unsupported charset. Contributed by Oleg Kalnichevski Release 4.2.2 ------------------- This is a maintenance release that fixes a number of bugs and regressions found since 4.2.1 including a major bug in the NIO module causing incorrect handling of outgoing Content-Length delimited messages larger than 2GB. Users of HttpCore 4.2 are advised to upgrade. Changelog ------------------- * [HTTPCORE-312] NIO length delimited content encoder incorrectly handles messages larger than 2GB. Contributed by Oleg Kalnichevski * [HTTPCORE-310] Fixed regression in DefaultConnectionReuseStrategy causing it to incorrectly flag connections as non-reusable after a 204, 205 or 304 response. Contributed by Oleg Kalnichevski * [HTTPCORE-309] Fixed regression in HttpAsyncRequestExecutor causing it to handle 204, 205 and 304 responses incorrectly by returning a message with an enclosed content body. Contributed by Oleg Kalnichevski * [HTTPCORE-306] I/O reactor TCP_NODELAY parameter now defaults to true. Contributed by Oleg Kalnichevski * [HTTPASYNC-21] request execution handler does not get closed in case of a premature HTTP exchange termination. Contributed by Oleg Kalnichevski * [HTTPCORE-303] ContentType made Serializable. Contributed by Oleg Kalnichevski Release 4.2.1 ------------------- This is a maintenance release that fixes a non-critical number of bugs found since 4.2. Users of HttpCore 4.2 are encouraged to upgrade. Changelog ------------------- * [HTTPCORE-299] ContentType should rely on Charset#name() instead of Charset#toString() for building header value. Contributed by Oleg Kalnichevski * [HTTPCORE-263] Under rare circumstances incorrectly delineated or garbled HTTP message can cause an IndexOutOfBoundsException in AbstractSessionInputBuffer#readLine() Contributed by Michael Pujos * Made connection pools use FIFO algorithm instead of LIFO when leasing / releasing persistent connections. Contributed by Oleg Kalnichevski * [HTTPCORE-298] Fixed non-blocking SSLIOSession state can getting out of sync with the underlying IOSession in case the I/O session is terminated by the I/O reactor rather than by the protocol handler. Contributed by Sandeep Tamhankar * Fixed NPE in StringEntity constructor thrown if ContentType#getCharset is null. Contributed by Oleg Kalnichevski Release 4.2 ------------------- This is the first stable (GA) release of HttpCore 4.2. The most notable features included in this release are connection pool components for blocking and non-blocking HTTP connections and new asynchronous client and server side protocol handlers. New protocol handling API used in conjunction with connection pooling components is expected to make development of asynchronous HTTP client agents and HTTP proxies easier and less error prone. Connection pool components are based on mature code migrated from HttpClient and HttpAsyncClient modules but have a slightly different API that makes a better use of Java standard concurrent primitives. Changelog ------------------- * Fixed HttpAsyncRequestExecutor incorrect execution of message exchanges that span across multiple hosts (for instance, in case of a request redirect). Contributed by Oleg Kalnichevski * AbstractHttpClientConnection#isResponseAvailable method now catches SocketTimeoutException and returns false. Contributed by Oleg Kalnichevski * [HTTPCORE-296] Server side connections (both blocking and non-blocking) can now handle entity enclosing requests without Content-Length and Transfer-Encoding headers. Contributed by Oleg Kalnichevski * [HTTPCORE-295] [HTTPCORE-288] Provided direct access to the underlying socket of non-blocking HTTP connection to allow modification of socket level settings such as TCP_NODELAY, SO_KEEPALIVE, TrafficClass, etc. Contributed by Oleg Kalnichevski * [HTTPCORE-289] HttpAsyncService fails to invoke Cancellable#cancel() when the ongoing HTTP exchange is aborted by the client. Contributed by Oleg Kalnichevski Incompatible changes -------------------- [Compared to release version 4.1.4] The following methods have been deprecated for some time now and have been deleted: org.apache.http.impl.SocketHttpServerConnection#createHttpDataReceiver(Socket, int, HttpParams) org.apache.http.impl.SocketHttpServerConnection#createHttpDataTransmitter(Socket, int, HttpParams) org.apache.http.protocol.HttpRequestHandlerRegistry#matchUriRequestPattern(String, String) The following classes have been deprecated for some while now and have been deleted: org.apache.http.nio.entity.ByteArrayNIOEntity org.apache.http.nio.entity.FileNIOEntity org.apache.http.nio.entity.HttpNIOEntity org.apache.http.nio.entity.StringNIOEntity org.apache.http.nio.protocol.NHttpClientHandlerBase org.apache.http.nio.protocol.NHttpServiceHandlerBase Release 4.2-BETA1 ------------------- This is the first BETA release of HttpCore 4.2. This release comes with completely redesigned and rewritten asynchronous protocol handlers. New protocol handling API used in conjunction with connection pooling components is expected to make development of asynchronous HTTP client agents and HTTP proxies easier and less error prone. Sample application shipped with the release include an example of an HTTP file server capable of direct channel (zero copy) data transfer and an example of a non-blocking, fully streaming reverse proxy. This release also incorporates bug fixes from the stable 4.1.x branch and includes an updated HttpCore tutorial. Release 4.1.4 ------------------- This is a maintenance release that fixes a number of bugs found since 4.1.3. It is also likely to be the last release in the 4.1.x branch. Changelog ------------------- * [HTTPCORE-286] Canceled I/O session can cause an IllegalStateException in BaseIOReactor#validate leading to an abnormal termination of the I/O reactor. Contributed by Oleg Kalnichevski * [HTTPCORE-257] Fixed incorrect results produced by DefaultConnectionReuseStrategy when handling response messages whose content entity has been decoded or modified by a protocol interceptor. Contributed by Oleg Kalnichevski * [HTTPCORE-283] Workaround for a bug causing termination of the I/O reactor in case of exception thrown by NHttpServiceHandler#requestReceived or NHttpClientHandler#responseReceived methods. A more comprehensive fix for the bug applied to the 4.2 branch. Contributed by Oleg Kalnichevski * [HTTPCORE-281] ResponseConnControl protocol interceptor does not correctly populate connection persistence control headers when sending a HTTP/1.1 response message in response to a HTTP/1.0 request message. Contributed by William R. Speirs * [HTTPCORE-282] The default value of the internal event mask of newly created non-blocking I/O is not correctly initialized, which causes the READ interest bit to get cleared in the interest op queuing mode unless the event mask is explicitly reset. Contributed by Sadeep Jayasumana and Oleg Kalnichevski * [HTTPCORE-268] Handle runtime exceptions thrown by SSLEngine. Contributed by Oleg Kalnichevski Release 4.2-ALPHA2 ------------------- This is the second ALPHA release of HttpCore 4.2. This release comes with completely redesigned and rewritten asynchronous protocol handlers. New protocol handling API used in conjunction with connection pooling components introduced in the previous ALPHA release is expected to make development of asynchronous HTTP client agents and HTTP proxies easier and less error prone. Sample application shipped with the release include an example of an HTTP file server capable of direct channel (zero copy) data transfer and an example of a non-blocking, fully streaming reverse proxy. We are kindly asking existing and prospective users of HttpCore to review and try out the new protocol handlers and give us feedback while the 4.2 API is still not final. If no major flaws are discovered the 4.2 API is expected to be frozen with the next BETA release. Please note that new features included in this release are still considered experimental and their API may change in the future ALPHA releases. This release also marks the end of support for Java 1.3. As of this release HttpCore requires Java 1.5 for all its components. Several classes and methods deprecated between versions 4.0-beta1 and 4.0 GA (more than two years ago) have been removed in this release. Changelog ------------------- * [HTTPCORE-270] Fixed IllegalStateException in AbstractSessionOutputBuffer and AbstractSessionInputBuffer. Contributed by William R. Speirs * [HTTPCORE-269] Connection pools incorrectly handle lease requests when the max limit for the given route has been exceeded and all connections in the route pool are stateful. Contributed by Oleg Kalnichevski Release 4.2-ALPHA1 ------------------- This is the first ALPHA release of 4.2. The most notable feature included in this release is support for connection pools of blocking and non-blocking HTTP connections. Connection pool components are based on mature code migrated from HttpClient and HttpAsyncClient modules but have a slightly different API that makes a better use of Java standard concurrent primitives. Support for connection pools in HttpCore is expected to make development of client and proxy HTTP services easier and less error prone. Please note that new features included in this release are still considered experimental and their API may change in the future ALPHA releases. This release also marks the end of support for Java 1.3. As of this release HttpCore requires Java 1.5 for all its components. Several classes and methods deprecated between versions 4.0-beta1 and 4.0 GA (more than two years ago) have been removed in this release. Changelog ------------------- * [HTTPCORE-268] Handle runtime exceptions thrown by SSLEngine. Contributed by Oleg Kalnichevski Release 4.1.3 ------------------- This is an emergency release that fixes a severe regression in the non-blocking SSL I/O code introduced in release 4.1.2. * [HTTPCORE-266] SSLIOSession does not correctly terminate if the opposite end shuts down connection without sending a 'close notify' message causing an infinite loop in the I/O dispatch thread. Contributed by Oleg Kalnichevski Release 4.1.2 ------------------- This is a patch release that fixes a number of bugs found in the previous version. Please note that several classes and methods deprecated between versions 4.0-beta1 and 4.0 GA (more than two years ago) will also be removed in the 4.2 branch. Users of 4.0.x versions are advised to upgrade and replace deprecated API calls following recommendations in javadocs. * [HTTPCORE-261] IOSession#setSocketTimeout() method does not reset the timeout count. Contributed by Oleg Kalnichevski * [HTTPCORE-260] Non-blocking SSL I/O session can terminate prematurely causing message body truncation when message content is chunk coded and the connection is closed on the opposite end. Contributed by Oleg Kalnichevski * [HTTPCORE-257] Fixed incorrect results produced by DefaultConnectionReuseStrategy when handling response messages whose content entity has been decoded or modified by a protocol interceptor. Contributed by Oleg Kalnichevski Release 4.1.1 ------------------- This is a patch release that fixes a number of non-critical issues found since release 4.1. This release marks the end of support for Java 1.3. As of release 4.2 HttpCore will require Java 1.5 for all its components. Please note that several classes and methods deprecated between versions 4.0-beta1 and 4.0 GA (more than two years ago) will also be removed in the 4.2 branch. Users of 4.0.x versions are advised to upgrade and replace deprecated API calls following recommendations in javadocs. * In case of an unexpected end of stream condition (the peer closed connection prematurely) truncated Content-Length delimited message bodies will cause an I/O exception. Application can still choose to catch and ignore ConnectionClosedException in order to accept partial message content. Contributed by Oleg Kalnichevski * [HTTPCORE-255]: Fixed resource management in InputStreamEntity#writeTo() Contributed by Oleg Kalnichevski * [HTTPCORE-254]: Erratic results from metrics (sebb) * [HTTPCORE-242]: Fixed NPE in AsyncNHttpClientHandler caused by an early response to an entity enclosing request. Contributed by Oleg Kalnichevski Release 4.1 ------------------- This is the first stable (GA) release of HttpCore 4.1. This release provides a compatibility mode with JREs that have a naive (broken) implementation of SelectionKey API and also improves compatibility with the Google Android platform. There has also been a number of performance related improvements and bug fixes in both blocking and non-blocking components. Changelog ------------------- * [HTTPCORE-240]: DefaultConnectingIOReactor leaks a socket descriptor if the session request fails. Contributed by Oleg Kalnichevski * [HTTPCORE-239]: The ChunkEncoder could request for a negative buffer limit causing an IllegalArgumentException. Contributed by Asankha Perera * [HTTPCORE-236]: SSLIOSession#isAppInputReady() does not check the status of the session input buffer. Contributed by Dmitry Lukyanov * [HTTPCORE-233]: EntityUtils#toString() and EntityUtils#toByteArray() to return null if HttpEntity#getContent() is null Contributed by Oleg Kalnichevski * [HTTPCORE-231] Fixed incorrect handling of HTTP entities by non-blocking LengthDelimitedDecoder when the Content-Length value is larger than Integer.MAX_VALUE. Contributed by Oleg Kalnichevski Release 4.1-BETA2 ------------------- This is the second BETA release of HttpCore 4.1. This is mainly a bug fix release that addresses a number of non-critical bugs. The most significant change in this release is deprecation of the HttpEntity#consumeContent() method and streamlining of connection management and resource deallocation by HTTP entities. Please refer to the javadocs for details. * [HTTPCORE-229] AbstractSessionInputBuffer#readLine(CharArrayBuffer) returns incorrect number of characters read by the method when using non-standard HTTP element charset. Contributed by Oleg Kalnichevski * Non-blocking connections can trigger #responseReady / #requestReady events by mistake when the underlying session is already closed. Contributed by Oleg Kalnichevski * [HTTPCORE-228] Fixed NPE in AsyncNHttpServiceHandler caused by entity enclosing requests if no matching request handler can be found. Contributed by Oleg Kalnichevski * [HTTPCORE-227] Fixed incorrect request / response count by non-blocking connections. Contributed by Harold Lee * [HTTPCORE-226] Improved compatibility of NIO components with Google Android. Contributed by Oleg Kalnichevski * ByteArrayBuffer, CharArrayBuffer, BasicHeader, BufferedHeader, HeaderGroup, BasicRequestLine, BasicStatusLine made Serializable. Contributed by Oleg Kalnichevski Release 4.1-BETA1 ------------------- This is the first BETA release of HttpCore 4.1. This release finalizes the API introduced in the 4.1 development branch. It also fixes a number of bugs discovered since the previous release and delivers a number of performance optimizations in the blocking HTTP transport components. The blocking HTTP transport is expected to be 5% to 10% faster compared to previous releases. * [HTTPCORE-222] Fixed Import-Package in the OSGi META-INF Contributed by Willem Jiang * [HTTPCORE-177] Reduce intermediate data buffering by reading large chunks of data directly from the underlying socket stream. This results in improved performance of blocking read operations. Contributed by Oleg Kalnichevski * [HTTPCORE-220] IdentityDecoder fails to detect end of stream when using file channels. Contributed by Asankha C. Perera * [HTTPCORE-218] ChunkEncoder#write method no longer returns incorrect value if the data to write is greater than the size of the internal buffer used by the encoder. Contributed by Richie Jefts * [HTTPCORE-209] Added parameter to set SO_REUSEADDR on sockets bound to a local address. Contributed by Oleg Kalnichevski * [HTTPCORE-207] SocketHttp*Connection classes can leak sockets if the connection is half-closed Contributed by David Koski Release 4.1-ALPHA1 ------------------- This is the first public release from the 4.1 branch of HttpCore. This release adds a number of new features, most notable being introduction of compatibility mode with IBM JREs and other JREs with naive (broken) implementation of SelectionKey API. Please note new classes and methods added in the 4.1 branch are still considered API unstable. * Ensure that an attempt is made to close out all active sessions gracefully in case of an abnormal shutdown of the I/O reactor. Contributed by Oleg Kalnichevski * [HTTPCORE-201] OSGi Export-Package to specify release version Contributed by Oleg Kalnichevski * [HTTPCORE-183] Added Thread-safe implementations of HttpParams and HttpProcessor - SyncBasicHttpParams and ImmutableHttpProcessor classes Contributed by Oleg Kalnichevski * [HTTPCORE-199] ContentInputStream implements InputStream#available(). Contributed by Oleg Kalnichevski * [HTTPCORE-195] Truncated chunk-coded streams can now be tolerated by catching and discarding TruncatedChunkException. Contributed by Oleg Kalnichevski * [HTTPCORE-155] Compatibility mode with IBM JRE and other JREs with naive (broken) implementation of SelectionKey. Contributed by Marc Beyerle and Oleg Kalnichevski * [HTTPCORE-191] Blocking HTTP connections are now capable of correctly preserving their internal state on SocketTimeoutExceptions, which makes it possible to continue reading from the connection after a socket timeout. Contributed by Oleg Kalnichevski * [HTTPCORE-190] ChunkedInputStream is now capable of correctly preserving its internal state on SocketTimeoutExceptions, which makes it possible to continue reading from the stream after a socket timeout. Contributed by Oleg Kalnichevski Release 4.0.1 ------------------- This is a patch release addressing a number of issues discovered since the 4.0 release. Users of NIO module are advised to upgrade. * [HTTPCORE-198] CONNECT request includes Host header for HTTP 1.1 connections. Contributed by Oleg Kalnichevski * [HTTPCORE-196] SSLIOSession now unwraps encrypted data more aggressively eliminating long pauses when receiving data over non-blocking connections. Contributed by Oleg Kalnichevski * [HTTPCORE-197] Fixed bug causing the non-blocking ChunkDecoder to report some data stream as truncated under special conditions. Contributed by Denis Rogov and Oleg Kalnichevski * SSLIOSession#isAppOutputReady and SSLIOSession#isAppInputReady no longer ignore the application event mask causing I/O event notifications for unrequested type of events. Contributed by Oleg Kalnichevski * [HTTPCORE-193] Fixed problem with SSLIOSession incorrectly handling of end-of-stream condition. Contributed by Asankha C. Perera and Oleg Kalnichevski Release 4.0 ------------------- This is the first stable (GA) release of HttpCore 4.0. This release mainly improves the documentation and fixes a few minor bugs reported since the previous release. HttpCore now comes with a complete tutorial presenting an in-depth coverage of the API. HttpCore is a set of low level HTTP transport components that can be used to build custom client and server side HTTP services with a minimal footprint. HttpCore supports two I/O models: blocking I/O model based on the classic Java I/O and non-blocking, event driven I/O model based on Java NIO. The blocking I/O model may be more appropriate for data intensive, low latency scenarios, whereas the non-blocking model may be more appropriate for high latency scenarios where raw data throughput is less important than the ability to handle thousands of simultaneous HTTP connections in a resource efficient manner. * [HTTPCORE-180] Fixed NPE in standard I/O event dispatchers when IOEventDispatch#disconnected fires before the session was fully initialized (IOEventDispatch#connected was not called). Contributed by Oleg Kalnichevski * [HTTPCORE-175] Chunk decoders no longer accept truncated chunks as valid input. Contributed by Oleg Kalnichevski Release 4.0 Beta 3 ------------------- The third BETA version of HttpComponents Core has been released. This is a maintenance release, which addresses a number of issues discovered since the previous release. The only significant new feature is an addition of an OSGi compliant bundle combining HttpCore and HttpCore NIO jars. * [HTTPCORE-173] Tolerate missing closing chunk if the chunk coded content is terminated by the end of stream (EOF) condition. Contributed by Oleg Kalnichevski * [HTTPCORE-174] Position is incremented twice in ContentLengthInputStream#skip(long) Contributed by Ildar Safarov * [HTTPCORE-125] OSGi bundle containing HttpCore & HttpCore NIO jars. Contributed by Oleg Kalnichevski * CancelledKeyException thrown in BaseIOReactor#validate() no longer causes a premature I/O reactor shutdown. Contributed by Oleg Kalnichevski * [HTTPCORE-172] Added #close() method to SharedInputBuffer and SharedOutputBuffer. The purpose of the new method is to close the buffer in case of normal / orderly termination of the underlying HTTP connection. Use #shutdown() method to force-close the buffer in case of abnormal / exceptional termination of the underlying connection. Contributed by Oleg Kalnichevski * [HTTPCORE-170] Fixed race condition in SharedOutputBuffer. Contributed by Jason Walton * [HTTPCORE-169] Fixed bug causing connecting I/O reactors to shut down due to ClosedChannelException if a pending session request is cancelled before the new channel has been registered with the selector. Contributed by Anders Wallgren * [HTTPCORE-167] Fixed handling the end of stream (EOF) condition in the #isStale() check of blocking HTTP connections. Contributed by Oleg Kalnichevski * [HTTPCORE-166] NIO reactors now maintain an audit log of fatal exceptions, which can be used to examine the cause and problems experienced during the shutdown process. Contributed by Oleg Kalnichevski * [HTTPCORE-165] Improved handling of CancelledKeyException in I/O reactors Contributed by Oleg Kalnichevski Release 4.0 Beta 2 ------------------- The second BETA version of HttpComponents Core has been released. This release adds a number of improvements to the NIO components, most notable being improved asynchronous client side and server side protocol handlers. There has been a number of important bug fixes in HttpCore NIO module, whereas HttpCore base module has had very few changes. All upstream projects dependent on HttpCore NIO are strongly advised to upgrade. * [HTTPCORE-163] Fixed AbstractMultiworkerIOReactor#execute() to correctly propagate the original I/O exception in case of an abnormal termination. Contributed by Patrick Moore * Changed behavior of IdentityDecoder & LengthDelimitedDecoder to throw an IOException if data is attempted to be written beyond the length of a FileChannel. Previously would write nothing. Contributed by Sam Berlin * Fixed bug in LengthDelimitedDecoder & IdentityDecoder that caused transfers to a FileChannel to overwrite arbitrary parts of the file, if data was buffered in SessionInputBuffer. Contributed by Sam Berlin * Fixed concurrency bug in the ThrottlingHttpServerHandler protocol handler. Contributed by Oleg Kalnichevski * Fixed bug in SharedInputBuffer that caused input events to be incorrectly suspended. Contributed by Asankha C. Perera * [HTTPCORE-150] Entity implementation that serializes a Java object Contributed by Andrea Selva * [HTTPCORE-157] ChunkedOutputStream#flush() now behaves consistently with the specification of OutputStream#flush(). Contributed by Oleg Kalnichevski * [HTTPCORE-147] Fixed handling of requests with partially consumed content in ThrottlingHttpServiceHandler. Contributed by Oleg Kalnichevski * [HTTPCORE-92] ChunkEncoder splits input data larger than available space in the session output buffer into smaller chunks instead of expanding the buffer. Contributed by Andrea Selva and Oleg Kalnichevski * [HTTPCORE-149] I/O reactors now count period of inactivity since the time of the last read or write operation. Previously only read operations resulted in timeout counter reset. Contributed by Oleg Kalnichevski * [HTTPCORE-148] Improved asynchronous server and client HTTP protocol handler implementations. Contributed by Sam Berlin * [HTTPCORE-143] Ensure the underlying channel is closed if the session request is canceled or times out. Contributed by Oleg Kalnichevski * [HTTPCORE-140] Fixed timeout handling in ThrottlingHttpServiceHandler. Contributed by Lorenzo Moretti and Oleg Kalnichevski Release 4.0 Beta 1 ------------------- The first BETA version of HttpComponents Core has been released. This release can be considered a major milestone, as it marks the end of API instability in HttpCore. As of this release the API compatibility between minor releases in 4.x codeline will be maintained. This release includes several major improvements such as enhanced HTTP message parsing API and optimized parser implementations, Java 5.0 compatibility for HttpCore NIO extensions. Upstream projects are strongly encouraged to upgrade to the latest release. The focus of the development efforts will be gradually shifting towards providing better test coverage, documentation and performance optimizations. Changelog: ---------- * [HTTPCORE-141] Session request timeout in DefaultConnectingIOReactor invalidates the request. Contributed by Oleg Kalnichevski * [HTTPCORE-137] DefaultHttpRequestFactory extended to support all methods specified in RFC 2616 (except CONNECT). Contributed by Oleg Kalnichevski * Replaced HTTP parameter linking with a simple child/parent stack. Contributed by Oleg Kalnichevski * [HTTPCORE-134] all serialVersionUID attributes are private Contributed by Roland Weber * [HTTPCORE-133] Clone support for basic HTTP message elements and non-streaming entities. Contributed by Oleg Kalnichevski * [HTTPCORE-127] Improved API for lifecycle management of listening I/O reactors. One can now suspend and resume listener endpoints. Contributed by Asankha C. Perera * [HTTPCORE-112] DefaultConnectionReuseStrategy interprets token sequences Contributed by Roland Weber * [HTTPCORE-122] new interface TokenIterator and basic implementation Contributed by Roland Weber * HttpCore NIOSSL classes moved to HttpCore NIO. Contributed by Oleg Kalnichevski * HttpCore NIO ported to Java 1.5. Contributed by Oleg Kalnichevski * [HTTPCORE-130] Fixed over-synchronization bug leading to a thread deadlock condition in SSL IOEventDispatch implementations. Contributed by Oleg Kalnichevski * [HTTPCORE-37] HttpParams beans Contributed by Stojce Dimski * [HTTPCORE-128] Simplified injection of custom NIO connection implementations. Contributed by Oleg Kalnichevski * [HTTPCORE-126] Improved HTTP message parsing API and optimized parser implementations. Contributed by Oleg Kalnichevski * Do not include "Connection: close" to 500 responses per default. Contributed by Oleg Kalnichevski * [HTTPCORE-121] new interface HeaderElementIterator Contributed by Andrea Selva * [HTTPCORE-123] Fixed problem with SSLSession losing buffered data, if the connection has been closed by the peer. Contributed by Risto Reinpõld Release 4.0 Alpha 6 ------------------- The sixth ALPHA version of HttpComponents Core has been released. This release sports an improved message parsing and formatting API in the base module and lots of incremental improvements and bug fixes in the NIO and NIOSSL modules. Based on the improved API, it is now possible to send and receive SIP messages with HttpComponents Core. HttpCore is now feature complete and we are planning to freeze the public APIs as of next release (BETA1). * [HTTPCORE-120] new interface HeaderIterator, available from HttpMessage Contributed by Roland Weber * [HTTPCORE-118] Purge closed sessions prior to opening new ones. This should reduce chances of running out of memory when opening and closing lots of NIO connections in a tight loop. Contributed by Oleg Kalnichevski * [HTTPCORE-117] Fixed bug preventing protocol handlers from closing timed out NIO connection when pending output (output session buffer is not empty). Contributed by Oleg Kalnichevski * [HTTPCORE-86] Allow for optional handling of runtime exceptions thrown by protocol handlers to ensure the I/O dispatch thread remains running. Contributed by Oleg Kalnichevski * [HTTPCORE-116] moved parameter names to interfaces Contributed by Roland Weber * [HTTPCORE-109] Improved shutdown process of the I/O reactors in NIO modules. I/O reactors now attempt to terminate connections gracefully before shutting down the underlying socket channels. Contributed by Oleg Kalnichevski * [HTTPCORE-107] allow sending and receiving of SIP messages Contributed by Roland Weber * [HTTPCORE-114]: Fixed incorrect handling of the end-of-stream condition in SSLIOSession. Oleg Kalnichevski * [HTTPCORE-110] refactored message parsing and formatting logic Contributed by Roland Weber * [HTTPCORE-113] Removed unnecessary target hostname resolution from non-blocking client protocol handlers. Oleg Kalnichevski * [HTTPCORE-108] Close all channels registered with the I/O reactor during shutdown. Fixed the problem with DefaultListeningIOReactor not releasing socket ports until JVM is restarted. Oleg Kalnichevski * [HTTPCORE-106] Pluggable HTTP message parsers and message writers Oleg Kalnichevski * [HTTPCORE-105] Consistent class names in base and NIO modules Oleg Kalnichevski * [HTTPCORE-100] revised HttpContext hierarchy Contributed by Roland Weber * [HTTPCORE-103] NIO connections now attempt to consume all available session data while parsing HTTP messages. This can potentially improve performance of non-blocking SSL connections. Contributed by Steffen Pingel * [HTTPCORE-102] Exceeding of maximum line length limit detected late Contributed by Steffen Pingel * [HTTPCORE-21] Transport and connection metrics Contributed by Andrea Selva and Oleg Kalnichevski * [HTTPCORE-91] new interceptor RequestDate, renamed constants in protocol.HTTP Contributed by Roland Weber * [HTTPCORE-90] Version detection based on build-time properties Contributed by Oleg Kalnichevski and Roland Weber * [HTTPCORE-88] Added convenience methods to HttpRequestInterceptorList, HttpResponseInterceptorList interfaces Contributed by Andrea Selva * [HTTPCORE-89]: Fixed bug in DefaultConnectingIOReactor causing incorrect handling of local (immediate) connections on some platforms (affects Sun Solaris 2.9 / Sparc and likely other Solaris 2.x platforms) Contributed by Sam Berlin Release 4.0 Alpha 5 ------------------- The fifth ALPHA version of HttpComponents Core has been released. This release delivers a number of incremental improvements across the board in all modules and adds several performance oriented features such as ability to transfer data directly between a file and a socket channels. HttpCore is almost fully feature complete now and we are likely to freeze the public APIs as of next release (BETA1). * [HTTPCORE-87] RuntimeExcpetions thrown in I/O worker threads are now correctly propagated to the I/O reactor. Contributed by Oleg Kalnichevski * [HTTPCORE-84]: Removed DateUtils/DateParseException from core. Contributed by Roland Weber * [HTTPCORE-63]: Made I/O select interval configurable for all default I/O reactor implementations. Contributed by Oleg Kalnichevski and Anders Wallgren * [HTTPCORE-82]: Revised linking of HttpParams to reduce potential for misuse. Method #setDefaults() removed from the HttpParams interface. Contributed by Roland Weber * [HTTPCORE-81]: Maximum line length and maximum header counts parameters are now correctly enforced in both base and NIO modules. Fixed maximum line length check when parsing folded header lines. Contributed by Steffen Pingel * Added HTTP client handler implementation that allocates fixed size content buffers upon initialization and is capable of throttling the rate of I/O events in order to make sure those content buffers do not get overflown. Contributed by Oleg Kalnichevski * [HTTPCORE-76]: Added IOSession#shutdown() method intended to force-close I/O sessions (primarily needed to terminate hung SSL connections). Contributed by Sandeep Tamhankar * [HTTPCORE-78]: Added ByteBufferAllocator interface that can be used to apply different ByteArray allocation strategies to session and content buffers. Use heap bound implementation for short-lived or variable in length (requiring frequent content re-allocation) buffers. Contributed by Steffen Pingel * [HTTPCORE-77]: The result of CharsetDecoder#decode() and CharsetEncoder#encode() was not checked for errors resulting in an infinite loop in SessionInputBuffer#readLine() and SessionOutputBuffer#writeLine() when malformed characters were processed. Contributed by Steffen Pingel * [HTTPCORE-71]: HttpParams can be copied. Contributed by Roland Weber * [HTTPCORE-75]: DefaultNHttpServerConnection and DefaultNHttpClientConnection now correctly terminate the underlying I/O session when closed. BufferingHttpServiceHandler now correctly applies connection keep-alive strategy when sending a response with no content body. Contributed by Steffen Pingel * [HTTPCORE-73]: Fixed bug preventing NHttpServiceHandler#responseReady and NHttpClientHandler#requestReady events from being fired if the HTTP message has no content body. Contributed by Steffen Pingel * [HTTPCORE-67]: Improved event listener interface Contributed by Oleg Kalnichevski * [HTTPCORE-43]: Support for FileChannel#transferFrom() and FileChannel#transferTo() methods. Direct coping from and to FileChannel is expected to improve performance of file bound operations Contributed by Andrea Selva * [HTTPCORE-66]: Fixed handling of HTTP HEAD methods Contributed by Steffen Pingel and Oleg Kalnichevski * [HTTPCORE-58]: NIO HTTP connections changed to throw checked ConnectionClosedException instead of unchecked IllegalStateException when an attempt is made to perform an I/O operation on a closed conection Contributed by Oleg Kalnichevski * [HTTPCORE-56]: DefaultConnectingIOReactor no longer terminates due to a CancelledKeyException, if a session request gets canceled before selection key is fully initialized. Contributed by Oleg Kalnichevski Release 4.0 Alpha 4 ------------------- The forth ALPHA version of HttpComponents Core has been released. The ALPHA4 release fixes a number of bugs and adds a number of improvements to HttpCore base and HttpCore NIO extensions. HttpCore NIO can be used to build HTTP services intended to handle thousands of simultaneous connections with a small number of I/O threads. This release also introduces NIOSSL extensions that can be used to extend HttpCore non-blocking transport components with ability to transparently encrypt data in transit using SSL/TLS protocol. * [HTTPCORE-49]: DefaultConnectingIOReactor can now correctly handle unresolved socket addresses. It no longer terminates with the UnresolvedAddressException runtime exception. Contributed by Oleg Kalnichevski * [HTTPCORE-42]: Added server side API for the expectation verification. Improved support for the 'expect: continue' handshake in HttpCore and HttpCore NIO. Contributed by Oleg Kalnichevski * [HTTPCORE-26]: Added SSL support for HttpCore NIO. Contributed by Oleg Kalnichevski * [HTTPCORE-40]: API classes no longer reference impl classes in module-main. Contributed by Roland Weber * [HTTPCORE-39]: Refactored HttpStatus, spun off [English]ReasonPhraseFactory. Contributed by Roland Weber * [HTTPCORE-32]: HttpRequestInterceptorList, HttpResponseInterceptorList Contributed by Roland Weber * [HTTPCORE-38]: Packages nio.impl.* are now impl.nio.*, same for examples. Contributed by Roland Weber * [HTTPCORE-27]: I/O reactors can now accept a thread factory as an optional parameter. Contributed by Oleg Kalnichevski * [HTTPCORE-36]: Fixed #setHandlers() method and matching of request URIs with a query part in HttpRequestHandlerRegistry Contributed by Oleg Kalnichevski * [HTTPCORE-28]: DefaultConnectingIOReactor now maintains a queue of connect requests and registers new sessions with the selector on the I/O thread. Contributed by Oleg Kalnichevski * [HTTPCORE-29] DefaultConnectingIOReactor changed to ensure IOExceptions are correctly propagated to the caller, if an exception is thrown while initializing a newly connected socket. Contributed by Oleg Kalnichevski * [HTTPCORE-24] Fixed bug in non-blocking connection implementations, which prevented the session buffer from being correctly flushed when the content coding process has been completed. Contributed by Oleg Kalnichevski * [HTTPCORE-23] Fixed threading bug in DefaultConnectingIOReactor. Contributed by Asankha C. Perera Release 4.0 Alpha 3 ------------------- The third ALPHA version of HttpCore has been released. The ALPHA3 release includes a number of API optimizations and improvements and introduces a set of NIO extensions to the HttpCore API. NIO extensions can be used to build HTTP services intended to handle thousands of simultaneous connections with a small number of I/O threads. * [HTTPCORE-15] Provided a interafce to access IP address of the local and remote end points. Contributed by Oleg Kalnichevski * [ HTTPCORE-14] Scheme, SocketFactory and SecureSocketFactory moved to HttpClient. Decoupled HttpHost and Scheme. Contributed by Oleg Kalnichevski * [HTTPCORE-13] Refactored HttpProcessor interface and related impl classes Contributed by Roland Weber * [HTTPCORE-11] Client connection interface no longer defines a specific method to open a connection. HTTP connections can now represent any abstract I/O transport such as those based on NIO API. Contributed by Oleg Kalnichevski * [HTTPCORE-10] Non-blocking (async) client side I/O transport based on NIO. Contributed by Oleg Kalnichevski * [HTTPCORE-9] Non-blocking (async) server side I/O transport based on NIO. Contributed by Oleg Kalnichevski * [HTTPCORE-7] ConnectionReuseStrategy interface changed to allow access to the HTTP execution context. Contributed by Roland Weber * [HTTPCORE-6] Header implementation allowing for performance short-cuts when serializing and deserializing HTTP headers. Contributed by Oleg Kalnichevski * [HTTPCORE-5] Header, HeaderElement, NameValuePair, RequestLine, StatusLine, HttpVersion changed to interfaces. API no longer contains any parsing and formatting code and does not imply any specific physical representation of HTTP messages and their elements. Contributed by Oleg Kalnichevski Release 4.0 Alpha 2 ------------------- This is a maintenance release that mostly fixes minor problems found since the previous release. The upstream projects are strongly encouraged use this release as a dependency while HttpCore undergoes another round of reviews and optimization in the SVN trunk Changelog: --------- * [HTTPCORE-4] optional header and line length limits to contain OOME risks Contributed by Oleg Kalnichevski Release 4.0 Alpha 1 ------------------- This release represents a complete redesign of the Jakarta Commons HttpClient 3.x API and a significant rewrite of the core HTTP components derived from HttpClient 3.0 code base. These components will form the foundation of the future releases of Jakarta HttpClient and can also be used separately to build custom client- and server-side HTTP services. httpcomponents-core-4.3.2/LICENSE.txt0100644 0000000 0000000 00000052462 12276755431 016132 0ustar000000000 0000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ========================================================================= This project contains annotations in the package org.apache.http.annotation which are derived from JCIP-ANNOTATIONS Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net and the Creative Commons Attribution License (http://creativecommons.org/licenses/by/2.5) Full text: http://creativecommons.org/licenses/by/2.5/legalcode License THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 1. Definitions "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License. "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License. "Licensor" means the individual or entity that offers the Work under the terms of this License. "Original Author" means the individual or entity who created the Work. "Work" means the copyrightable work of authorship offered under the terms of this License. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. 2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws. 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; to create and reproduce Derivative Works; to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works; to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works. For the avoidance of doubt, where the work is a musical composition: Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work. Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions). Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions). The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved. 4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(b), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(b), as requested. If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit. 5. Representations, Warranties and Disclaimer UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. Termination This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 8. Miscellaneous Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. httpcomponents-core-4.3.2/pom.xml0100644 0000000 0000000 00000027572 12276755426 015634 0ustar000000000 0000000 project org.apache.httpcomponents 7 ../project/pom.xml 4.0.0 httpcomponents-core Apache HttpComponents Core 4.3.2 Core components to build HTTP enabled services http://hc.apache.org/httpcomponents-core 2005 pom The Apache Software Foundation http://www.apache.org/ Apache License, Version 2.0 LICENSE.txt repo Jira http://issues.apache.org/jira/browse/HTTPCORE scm:svn:https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.3.2 scm:svn:https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.3.2 https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.3.2 httpcore httpcore-nio httpcore-osgi httpcore-ab false 4.9 1.8.5 1.1.3 4.3 1 junit junit ${junit.version} test org.mockito mockito-core ${mockito.version} test commons-logging commons-logging ${commons-logging.version} test maven-jar-plugin HttpComponents ${project.name} ${project.version} The Apache Software Foundation HttpComponents ${project.name} ${project.version} The Apache Software Foundation org.apache ${project.url} maven-source-plugin attach-sources jar maven-javadoc-plugin attach-javadocs jar true ${maven.compiler.source} http://download.oracle.com/javase/1.5.0/docs/api/ maven-site-plugin com.agilejava.docbkx docbkx-maven-plugin org.docbook docbook-xml 4.4 runtime tutorial-site generate-html generate-pdf pre-site index.xml true true src/docbkx/resources/xsl/fopdf.xsl src/docbkx/resources/xsl/html_chunk.xsl css/hc-tutorial.css version ${project.version} maven-resources-plugin copy-resources pre-site copy-resources ${basedir}/target/site/examples src/examples false org.apache.maven.plugins maven-checkstyle-plugin 2.9.1 org.apache.httpcomponents hc-stylecheck ${hc.stylecheck.version} UTF-8 validate-main validate hc-stylecheck/default.xml hc-stylecheck/asl2.header true true false ${basedir}/src/main checkstyle validate-test validate hc-stylecheck/default.xml hc-stylecheck/asl2.header true true false ${basedir}/src/test checkstyle validate-examples validate hc-stylecheck/minimal.xml hc-stylecheck/asl2.header true true false ${basedir}/src/examples checkstyle org.codehaus.mojo clirr-maven-plugin ${hc.clirr.version} ${api.comparison.version} maven-project-info-reports-plugin ${hc.project-info.version} false dependency-management issue-tracking license scm summary org.codehaus.mojo clirr-maven-plugin ${hc.clirr.version} ${api.comparison.version} httpcomponents-core-4.3.2/README.txt0100644 0000000 0000000 00000004145 12276755426 016004 0ustar000000000 0000000 Apache HttpComponents Core ========================== Welcome to the HttpCore component of the Apache HttpComponents project. Building Instructions --------------------- For building from source instructions please refer to BUILDING.txt. Dependencies ------------ HttpCore requires Java 1.5 compatible runtime. Licensing --------- Apache HttpComponents Core is licensed under the Apache License 2.0. See the files called LICENSE.txt and NOTICE.txt for more information. Cryptographic Software Notice ----------------------------- This distribution may include software that has been designed for use with cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See for more information. The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS), has classified this software as Export Commodity Control Number (ECCN) 5D002.C.1, which includes information security software using or performing cryptographic functions with asymmetric algorithms. The form and manner of this Apache Software Foundation distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code. The following provides more details on the included software that may be subject to export controls on cryptographic software: Apache HttpComponents Core interfaces with the Java Secure Socket Extension (JSSE) API to provide - HTTPS support Apache HttpComponents Core does not include any implementation of JSSE. Contact ------- o For general information visit the main project site at http://hc.apache.org/ o For current status information visit the status page at http://hc.apache.org/status.html httpcomponents-core-4.3.2/NOTICE.txt0100644 0000000 0000000 00000000475 12276755431 016026 0ustar000000000 0000000 Apache HttpComponents Core Copyright 2005-2014 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). This project contains annotations derived from JCIP-ANNOTATIONS Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net httpcomponents-core-4.3.2/BUILDING.txt0100644 0000000 0000000 00000002203 12276755426 016235 0ustar000000000 0000000 Building HttpComponents Core ============================ (1) Requisites -------------- JDK 1.5+ is required in order to compile and run HttpCore. HttpCore utilizes Maven as a distribution management and packaging tool. Version 3.0.3 or later is required. Maven installation and configuration instructions can be found here: http://maven.apache.org/run-maven/index.html (2) Executing test cases Execute the following command in order to compile and test the components mvn test (3) Building packages Execute the following command in order to build the JAR packages and install them to the local repository: mvn install The JAR packages can be found in the target folders of their respective modules httpcore/target/httpcore-.jar httpcore-nio/target/httpcore-nio-.jar httpcore-osgi/target/org.apache.httpcomponents.httpcore_.jar where is the release version (4) Building documentation Execute the following command in order to generate javadoc: mvn javadoc:aggregate Execute the following command in order to generate the tutorial in html and pdf formats mvn docbkx:generate-pdf docbkx:generate-html httpcomponents-core-4.3.2/httpcore/0040755 0000000 0000000 00000000000 12276755460 016133 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/pom.xml0100644 0000000 0000000 00000010765 12276755426 017460 0ustar000000000 0000000 4.0.0 org.apache.httpcomponents httpcomponents-core 4.3.2 httpcore Apache HttpCore 2005 HttpComponents Core (blocking I/O) http://hc.apache.org/httpcomponents-core-ga jar junit junit test org.mockito mockito-core test commons-logging commons-logging test src/main/resources true **/*.properties org.codehaus.mojo build-helper-maven-plugin 1.8 add-source generate-sources add-source src/main/java-deprecated maven-javadoc-plugin ${hc.javadoc.version} true ${maven.compiler.source} http://download.oracle.com/javase/1.5.0/docs/api/ javadoc maven-project-info-reports-plugin ${hc.project-info.version} false dependencies dependency-info summary maven-jxr-plugin ${hc.jxr.version} maven-surefire-report-plugin ${hc.surefire-report.version} httpcomponents-core-4.3.2/httpcore/src/0040755 0000000 0000000 00000000000 12276755422 016720 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/0040755 0000000 0000000 00000000000 12276755423 017645 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/resources/0040755 0000000 0000000 00000000000 12276755422 021656 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/resources/org/0040755 0000000 0000000 00000000000 12276755422 022445 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/resources/org/apache/0040755 0000000 0000000 00000000000 12276755422 023666 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/resources/org/apache/http/0040755 0000000 0000000 00000000000 12276755422 024645 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/resources/org/apache/http/version.properties0100644 0000000 0000000 00000001620 12276755422 030444 0ustar000000000 0000000 # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # info.module = httpcore info.release = ${pom.version} info.timestamp = ${mvn.timestamp} # timestamp requires Maven 2.1 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/0040755 0000000 0000000 00000000000 12276755422 022663 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/0040755 0000000 0000000 00000000000 12276755422 023452 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/0040755 0000000 0000000 00000000000 12276755422 024673 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/0040755 0000000 0000000 00000000000 12276755423 025653 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/0040755 0000000 0000000 00000000000 12276755423 027136 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000153 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpProtocolParams.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpProtocolParam0100644 0000000 0000000 00000021030 12276755423 032474 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; import java.nio.charset.CodingErrorAction; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; /** * Utility class for accessing protocol parameters in {@link HttpParams}. * * @since 4.0 * * @deprecated (4.3) use configuration classes provided 'org.apache.http.config' * and 'org.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 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 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 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 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); } } ././@LongLink0100644 0000000 0000000 00000000156 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpProtocolParamBean.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpProtocolParam0100644 0000000 0000000 00000004612 12276755423 032503 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; import org.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 'org.apache.http.config' * and 'org.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); } } ././@LongLink0100644 0000000 0000000 00000000160 12276757360 011647 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpConnectionParamBean.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpConnectionPar0100644 0000000 0000000 00000004762 12276755423 032471 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 'org.apache.http.config' * and 'org.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); } } ././@LongLink0100644 0000000 0000000 00000000154 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/DefaultedHttpParams.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/DefaultedHttpPara0100644 0000000 0000000 00000012662 12276755423 032426 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; import java.util.HashSet; import java.util.Set; import org.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 'org.apache.http.config' * and 'org.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 * @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 * @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 * @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"); } } ././@LongLink0100644 0000000 0000000 00000000155 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpConnectionParams.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpConnectionPar0100644 0000000 0000000 00000020366 12276755423 032467 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; import org.apache.http.util.Args; /** * Utility class for accessing connection parameters in {@link HttpParams}. * * @since 4.0 * * @deprecated (4.3) use configuration classes provided 'org.apache.http.config' * and 'org.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 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 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 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 -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 -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 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 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 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); } } ././@LongLink0100644 0000000 0000000 00000000154 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/SyncBasicHttpParams.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/SyncBasicHttpPara0100644 0000000 0000000 00000005270 12276755423 032404 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; import org.apache.http.annotation.ThreadSafe; /** * Thread-safe extension of the {@link BasicHttpParams}. * * @since 4.1 * * @deprecated (4.3) use configuration classes provided 'org.apache.http.config' * and 'org.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(); } } ././@LongLink0100644 0000000 0000000 00000000156 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpAbstractParamBean.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/params/HttpAbstractParam0100644 0000000 0000000 00000003160 12276755423 032442 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; import org.apache.http.util.Args; /** * @since 4.0 * * @deprecated (4.3) use configuration classes provided 'org.apache.http.config' * and 'org.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"); } } httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/0040755 0000000 0000000 00000000000 12276755423 026614 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000162 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/DefaultHttpServerConnection.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/DefaultHttpServerCo0100644 0000000 0000000 00000005026 12276755422 032433 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.IOException; import java.net.Socket; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.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); } } ././@LongLink0100644 0000000 0000000 00000000163 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/AbstractHttpServerConnection.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/AbstractHttpServerC0100644 0000000 0000000 00000026562 12276755422 032443 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.IOException; import org.apache.http.HttpConnectionMetrics; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.entity.DisallowIdentityContentLengthStrategy; import org.apache.http.impl.entity.EntityDeserializer; import org.apache.http.impl.entity.EntitySerializer; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.io.DefaultHttpRequestParser; import org.apache.http.impl.io.HttpResponseWriter; import org.apache.http.io.EofSensor; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.io.SessionInputBuffer; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * 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 org.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}
  • *
  • {@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}
  • *
  • {@link org.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 org.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 org.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 org.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 org.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; } } ././@LongLink0100644 0000000 0000000 00000000161 12276757360 011650 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/SocketHttpServerConnection.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/SocketHttpServerCon0100644 0000000 0000000 00000021671 12276755423 032462 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.HttpInetConnection; import org.apache.http.impl.io.SocketInputBuffer; import org.apache.http.impl.io.SocketOutputBuffer; import org.apache.http.io.SessionInputBuffer; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.Asserts; @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 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(); } } } ././@LongLink0100644 0000000 0000000 00000000161 12276757360 011650 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/SocketHttpClientConnection.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/SocketHttpClientCon0100644 0000000 0000000 00000022375 12276755422 032433 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.HttpInetConnection; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.io.SocketInputBuffer; import org.apache.http.impl.io.SocketOutputBuffer; import org.apache.http.io.SessionInputBuffer; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * 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 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(); } } } ././@LongLink0100644 0000000 0000000 00000000162 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/DefaultHttpClientConnection.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/DefaultHttpClientCo0100644 0000000 0000000 00000004726 12276755422 032411 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.IOException; import java.net.Socket; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.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); } } ././@LongLink0100644 0000000 0000000 00000000163 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/AbstractHttpClientConnection.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/AbstractHttpClientC0100644 0000000 0000000 00000027370 12276755422 032411 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.IOException; import java.net.SocketTimeoutException; import org.apache.http.HttpClientConnection; import org.apache.http.HttpConnectionMetrics; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpStatus; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.entity.EntityDeserializer; import org.apache.http.impl.entity.EntitySerializer; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.io.DefaultHttpResponseParser; import org.apache.http.impl.io.HttpRequestWriter; import org.apache.http.io.EofSensor; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.io.SessionInputBuffer; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * 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 org.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}
  • *
  • {@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}
  • *
  • {@link org.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 org.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 org.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 org.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 org.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; } } httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/0040755 0000000 0000000 00000000000 12276755422 030127 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000156 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/EntitySerializer.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/EntitySerial0100644 0000000 0000000 00000011157 12276755422 032470 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import java.io.IOException; import java.io.OutputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.annotation.Immutable; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.io.ChunkedOutputStream; import org.apache.http.impl.io.ContentLengthOutputStream; import org.apache.http.impl.io.IdentityOutputStream; import org.apache.http.io.SessionOutputBuffer; import org.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 org.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(); } } ././@LongLink0100644 0000000 0000000 00000000160 12276757360 011647 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/EntityDeserializer.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/EntityDeseri0100644 0000000 0000000 00000012736 12276755422 032470 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.annotation.Immutable; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.io.ChunkedInputStream; import org.apache.http.impl.io.ContentLengthInputStream; import org.apache.http.impl.io.IdentityInputStream; import org.apache.http.io.SessionInputBuffer; import org.apache.http.protocol.HTTP; import org.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 org.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/0040755 0000000 0000000 00000000000 12276755422 027222 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000164 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/AbstractSessionInputBuffer.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/AbstractSessionI0100644 0000000 0000000 00000033632 12276755422 032371 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.Consts; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.BufferInfo; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.io.SessionInputBuffer; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; import org.apache.http.util.ByteArrayBuffer; import org.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 -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, * 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; } } ././@LongLink0100644 0000000 0000000 00000000153 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/SocketInputBuffer.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/SocketInputBuffe0100644 0000000 0000000 00000006516 12276755422 032372 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.net.Socket; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.EofSensor; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * {@link org.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 0 it is set to the value of * {@link Socket#getReceiveBufferSize()}. If resultant number is less * than 1024 it is set to 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; } } ././@LongLink0100644 0000000 0000000 00000000154 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpResponseWriter.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpResponseWrit0100644 0000000 0000000 00000004267 12276755422 032457 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.message.LineFormatter; import org.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); } } ././@LongLink0100644 0000000 0000000 00000000165 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/AbstractSessionOutputBuffer.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/AbstractSessionO0100644 0000000 0000000 00000024633 12276755422 032400 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.Consts; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.BufferInfo; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; import org.apache.http.util.ByteArrayBuffer; import org.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; } } ././@LongLink0100644 0000000 0000000 00000000154 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpResponseParser.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpResponsePars0100644 0000000 0000000 00000007341 12276755422 032433 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.HttpResponseFactory; import org.apache.http.NoHttpResponseException; import org.apache.http.ParseException; import org.apache.http.StatusLine; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.LineParser; import org.apache.http.message.ParserCursor; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.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 org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}
  • *
  • {@link org.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 org.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); } } ././@LongLink0100644 0000000 0000000 00000000153 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpRequestParser.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpRequestParse0100644 0000000 0000000 00000007226 12276755422 032434 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.HttpRequestFactory; import org.apache.http.ParseException; import org.apache.http.RequestLine; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.LineParser; import org.apache.http.message.ParserCursor; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.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 org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}
  • *
  • {@link org.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 org.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); } } ././@LongLink0100644 0000000 0000000 00000000154 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/SocketOutputBuffer.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/SocketOutputBuff0100644 0000000 0000000 00000004746 12276755422 032431 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.net.Socket; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * {@link org.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 0 it is set to the value of * {@link Socket#getSendBufferSize()}. If resultant number is less * than 1024 it is set to 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); } } ././@LongLink0100644 0000000 0000000 00000000153 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpRequestWriter.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpRequestWrite0100644 0000000 0000000 00000004260 12276755422 032447 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.HttpRequest; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.message.LineFormatter; import org.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/0040755 0000000 0000000 00000000000 12276755423 027514 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000165 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/HttpRequestHandlerRegistry.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/HttpRequestHand0100644 0000000 0000000 00000006736 12276755423 032533 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.util.Map; import org.apache.http.annotation.ThreadSafe; import org.apache.http.util.Args; /** * Maintains a map of HTTP request handlers keyed by a request URI pattern. *
* Patterns may have three formats: *
    *
  • *
  • *
  • *<uri>
  • *
  • <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); } } ././@LongLink0100644 0000000 0000000 00000000157 12276757360 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/DefaultedHttpContext.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/DefaultedHttpCo0100644 0000000 0000000 00000005334 12276755423 032460 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.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(); } } ././@LongLink0100644 0000000 0000000 00000000153 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/ExecutionContext.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/ExecutionContex0100644 0000000 0000000 00000005277 12276755423 032573 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.HttpConnection} object that * represents the actual HTTP connection. */ public static final String HTTP_CONNECTION = "http.connection"; /** * Attribute name of a {@link org.apache.http.HttpRequest} object that * represents the actual HTTP request. */ public static final String HTTP_REQUEST = "http.request"; /** * Attribute name of a {@link org.apache.http.HttpResponse} object that * represents the actual HTTP response. */ public static final String HTTP_RESPONSE = "http.response"; /** * Attribute name of a {@link org.apache.http.HttpHost} object that * represents the connection target. */ public static final String HTTP_TARGET_HOST = "http.target_host"; /** * Attribute name of a {@link org.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"; } ././@LongLink0100644 0000000 0000000 00000000155 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/BasicHttpProcessor.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/BasicHttpProces0100644 0000000 0000000 00000020251 12276755423 032471 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.annotation.NotThreadSafe; import org.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; } } ././@LongLink0100644 0000000 0000000 00000000157 12276757360 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/SyncBasicHttpContext.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/protocol/SyncBasicHttpCo0100644 0000000 0000000 00000004167 12276755423 032444 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/util/0040755 0000000 0000000 00000000000 12276755422 026627 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000145 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/util/ExceptionUtils.javahttpcomponents-core-4.3.2/httpcore/src/main/java-deprecated/org/apache/http/util/ExceptionUtils.java0100644 0000000 0000000 00000005470 12276755422 032454 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 Method allowing access to * {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable}, * or null if the method * does not exist. * * @return A Method for Throwable.initCause, or * 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() { } } httpcomponents-core-4.3.2/httpcore/src/main/java/0040755 0000000 0000000 00000000000 12276755423 020566 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/0040755 0000000 0000000 00000000000 12276755423 021355 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/0040755 0000000 0000000 00000000000 12276755423 022576 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/0040755 0000000 0000000 00000000000 12276755426 023560 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/ProtocolException.java0100644 0000000 0000000 00000004420 12276755425 030077 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 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 Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public ProtocolException(final String message, final Throwable cause) { super(message, cause); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpEntity.java0100644 0000000 0000000 00000017625 12276755423 026544 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 true if chunked encoding is preferred for this * entity, or 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 * 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 * 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 IllegalStateException * if content stream cannot be created. * * @see #isRepeatable() */ InputStream getContent() throws IOException, IllegalStateException; /** * 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 true. Self-contained entities should return * false. Wrapping entities should delegate this call * to the wrapped entity. * * @return true if the entity content is streamed, * 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 org.apache.http.util.EntityUtils#consume(HttpEntity)} * * @see #getContent() and #writeTo(OutputStream) */ @Deprecated void consumeContent() throws IOException; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/MethodNotSupportedException.java0100644 0000000 0000000 00000004122 12276755423 032102 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public MethodNotSupportedException(final String message, final Throwable cause) { super(message, cause); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpMessage.java0100644 0000000 0000000 00000015662 12276755423 026653 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import org.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 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 null is * returned. * * @param name the name of the header to return. * @return the first header whose name property equals name * or 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 null is returned. * * @param name the name of the header to return. * @return the last header whose name property equals name. * or 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 * 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 'org.apache.http.config' * and 'org.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 'org.apache.http.config' * and 'org.apache.http.client.config' */ @Deprecated void setParams(HttpParams params); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpClientConnection.java0100644 0000000 0000000 00000007465 12276755423 030527 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpConnectionMetrics.java0100644 0000000 0000000 00000004371 12276755426 030713 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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, * null if the metric cannot not found. */ Object getMetric(String metricName); /** * Resets the counts * */ void reset(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpRequestInterceptor.java0100644 0000000 0000000 00000005224 12276755425 031131 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import java.io.IOException; import org.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpHost.java0100644 0000000 0000000 00000020673 12276755423 026202 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import java.io.Serializable; import java.net.InetAddress; import java.util.Locale; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; import org.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 a new {@link HttpHost HttpHost}, specifying all values. * Constructor for HttpHost. * * @param hostname the hostname (IP or DNS name) * @param port the port number. * -1 indicates the scheme default port. * @param scheme the name of the scheme. * null indicates the * {@link #DEFAULT_SCHEME_NAME default scheme} */ public HttpHost(final String hostname, final int port, final String scheme) { super(); this.hostname = Args.notBlank(hostname, "Host name"); this.lcHostname = hostname.toLowerCase(Locale.ENGLISH); if (scheme != null) { this.schemeName = scheme.toLowerCase(Locale.ENGLISH); } else { this.schemeName = DEFAULT_SCHEME_NAME; } this.port = port; this.address = null; } /** * Creates a new {@link HttpHost HttpHost}, with default scheme. * * @param hostname the hostname (IP or DNS name) * @param port the port number. * -1 indicates the scheme default port. */ public HttpHost(final String hostname, final int port) { this(hostname, port, null); } /** * Creates a new {@link HttpHost HttpHost}, with default scheme and port. * * @param hostname the hostname (IP or DNS name) */ public HttpHost(final String hostname) { this(hostname, -1, null); } /** * Creates a new {@link HttpHost HttpHost}, specifying all values. * Constructor for HttpHost. * * @param address the inet address. * @param port the port number. * -1 indicates the scheme default port. * @param scheme the name of the scheme. * null indicates the * {@link #DEFAULT_SCHEME_NAME default scheme} * * @since 4.3 */ public HttpHost(final InetAddress address, final int port, final String scheme) { super(); this.address = Args.notNull(address, "Inet address"); this.hostname = address.getHostAddress(); this.lcHostname = this.hostname.toLowerCase(Locale.ENGLISH); if (scheme != null) { this.schemeName = scheme.toLowerCase(Locale.ENGLISH); } else { this.schemeName = DEFAULT_SCHEME_NAME; } this.port = port; } /** * Creates a new {@link HttpHost HttpHost}, with default scheme. * * @param address the inet address. * @param port the port number. * -1 indicates the scheme default port. * * @since 4.3 */ public HttpHost(final InetAddress address, final int port) { this(address, port, null); } /** * Creates a new {@link HttpHost HttpHost}, with default scheme and port. * * @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 -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, * 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 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); } 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); return hash; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpHeaders.java0100644 0000000 0000000 00000016737 12276755425 026650 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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"; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/StatusLine.java0100644 0000000 0000000 00000003443 12276755424 026515 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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: StatusLine.java 937295 2010-04-23 13:44:00Z olegk $ * * @since 4.0 */ public interface StatusLine { ProtocolVersion getProtocolVersion(); int getStatusCode(); String getReasonPhrase(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/ProtocolVersion.java0100644 0000000 0000000 00000021243 12276755425 027570 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import java.io.Serializable; import org.apache.http.annotation.Immutable; import org.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 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 true if the argument is the same protocol version, * 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 true if {@link #compareToVersion compareToVersion} * can be called with the argument, 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 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 true if this protocol version is * {@link #isComparable comparable} to the argument * and {@link #compareToVersion compares} as greater or equal, * 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 true if this protocol version is * {@link #isComparable comparable} to the argument * and {@link #compareToVersion compares} as less or equal, * 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/MalformedChunkCodingException.java0100644 0000000 0000000 00000003476 12276755424 032332 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpRequestFactory.java0100644 0000000 0000000 00000003007 12276755423 030235 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpVersion.java0100644 0000000 0000000 00000006523 12276755423 026710 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import java.io.Serializable; import org.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/NoHttpResponseException.java0100644 0000000 0000000 00000003261 12276755423 031231 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpInetConnection.java0100644 0000000 0000000 00000002745 12276755423 030204 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/Header.java0100644 0000000 0000000 00000004702 12276755424 025611 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 */ HeaderElement[] getElements() throws ParseException; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpEntityEnclosingRequest.java0100644 0000000 0000000 00000003741 12276755426 031754 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HeaderElement.java0100644 0000000 0000000 00000006233 12276755424 027124 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/ConnectionReuseStrategy.java0100644 0000000 0000000 00000005453 12276755423 031252 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import org.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 false, the caller MUST * close the connection to correctly comply with the HTTP protocol. * If it returns 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, 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 true if the connection is allowed to be reused, or * false if it MUST NOT be reused */ boolean keepAlive(HttpResponse response, HttpContext context); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HeaderElementIterator.java0100644 0000000 0000000 00000003554 12276755425 030642 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 true if there is another header element, * false otherwise */ 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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/package-info.java0100644 0000000 0000000 00000003471 12276755426 026751 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.HttpMessage message} including it's * {@link org.apache.http.Header headers} and optional * {@link org.apache.http.HttpEntity entity}, and * {@link org.apache.http.HttpConnection connections} * over which messages are sent. In order to prepare messages * before sending or after receiving, there are interceptors for * {@link org.apache.http.HttpRequestInterceptor requests} and * {@link org.apache.http.HttpResponseInterceptor responses}. */ package org.apache.http; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpRequest.java0100644 0000000 0000000 00000003544 12276755426 026716 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpConnection.java0100644 0000000 0000000 00000007116 12276755423 027361 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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. */ 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 true if attempts to use this connection are * likely to succeed, or 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, * 0 if timeout is disabled or -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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/NameValuePair.java0100644 0000000 0000000 00000003012 12276755424 027103 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/ConnectionClosedException.java0100644 0000000 0000000 00000003255 12276755425 031534 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } } ././@LongLink0100644 0000000 0000000 00000000146 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/UnsupportedHttpVersionException.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/UnsupportedHttpVersionException.jav0100644 0000000 0000000 00000003433 12276755425 032676 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpConnectionFactory.java0100644 0000000 0000000 00000002673 12276755426 030717 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HeaderIterator.java0100644 0000000 0000000 00000003457 12276755424 027331 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 true if there is another header, * false otherwise */ 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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/Consts.java0100644 0000000 0000000 00000003473 12276755423 025675 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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() { } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/TruncatedChunkException.java0100644 0000000 0000000 00000003215 12276755424 031220 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpResponseFactory.java0100644 0000000 0000000 00000004720 12276755426 030411 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import org.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 * 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 * null to use the default locale * * @return the new response with the argument status line */ HttpResponse newHttpResponse(StatusLine statusline, HttpContext context); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpServerConnection.java0100644 0000000 0000000 00000006272 12276755423 030552 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpResponseInterceptor.java0100644 0000000 0000000 00000005232 12276755423 031274 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import java.io.IOException; import org.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/ReasonPhraseCatalog.java0100644 0000000 0000000 00000003405 12276755423 030304 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 null if unknown */ String getReason(int status, Locale loc); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpStatus.java0100644 0000000 0000000 00000017206 12276755426 026551 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 --- /** 100 Continue (HTTP/1.1 - RFC 2616) */ public static final int SC_CONTINUE = 100; /** 101 Switching Protocols (HTTP/1.1 - RFC 2616)*/ public static final int SC_SWITCHING_PROTOCOLS = 101; /** 102 Processing (WebDAV - RFC 2518) */ public static final int SC_PROCESSING = 102; // --- 2xx Success --- /** 200 OK (HTTP/1.0 - RFC 1945) */ public static final int SC_OK = 200; /** 201 Created (HTTP/1.0 - RFC 1945) */ public static final int SC_CREATED = 201; /** 202 Accepted (HTTP/1.0 - RFC 1945) */ public static final int SC_ACCEPTED = 202; /** 203 Non Authoritative Information (HTTP/1.1 - RFC 2616) */ public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; /** 204 No Content (HTTP/1.0 - RFC 1945) */ public static final int SC_NO_CONTENT = 204; /** 205 Reset Content (HTTP/1.1 - RFC 2616) */ public static final int SC_RESET_CONTENT = 205; /** 206 Partial Content (HTTP/1.1 - RFC 2616) */ public static final int SC_PARTIAL_CONTENT = 206; /** * 207 Multi-Status (WebDAV - RFC 2518) or 207 Partial Update * OK (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?) */ public static final int SC_MULTI_STATUS = 207; // --- 3xx Redirection --- /** 300 Mutliple Choices (HTTP/1.1 - RFC 2616) */ public static final int SC_MULTIPLE_CHOICES = 300; /** 301 Moved Permanently (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_PERMANENTLY = 301; /** 302 Moved Temporarily (Sometimes Found) (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_TEMPORARILY = 302; /** 303 See Other (HTTP/1.1 - RFC 2616) */ public static final int SC_SEE_OTHER = 303; /** 304 Not Modified (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_MODIFIED = 304; /** 305 Use Proxy (HTTP/1.1 - RFC 2616) */ public static final int SC_USE_PROXY = 305; /** 307 Temporary Redirect (HTTP/1.1 - RFC 2616) */ public static final int SC_TEMPORARY_REDIRECT = 307; // --- 4xx Client Error --- /** 400 Bad Request (HTTP/1.1 - RFC 2616) */ public static final int SC_BAD_REQUEST = 400; /** 401 Unauthorized (HTTP/1.0 - RFC 1945) */ public static final int SC_UNAUTHORIZED = 401; /** 402 Payment Required (HTTP/1.1 - RFC 2616) */ public static final int SC_PAYMENT_REQUIRED = 402; /** 403 Forbidden (HTTP/1.0 - RFC 1945) */ public static final int SC_FORBIDDEN = 403; /** 404 Not Found (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_FOUND = 404; /** 405 Method Not Allowed (HTTP/1.1 - RFC 2616) */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** 406 Not Acceptable (HTTP/1.1 - RFC 2616) */ public static final int SC_NOT_ACCEPTABLE = 406; /** 407 Proxy Authentication Required (HTTP/1.1 - RFC 2616)*/ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** 408 Request Timeout (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TIMEOUT = 408; /** 409 Conflict (HTTP/1.1 - RFC 2616) */ public static final int SC_CONFLICT = 409; /** 410 Gone (HTTP/1.1 - RFC 2616) */ public static final int SC_GONE = 410; /** 411 Length Required (HTTP/1.1 - RFC 2616) */ public static final int SC_LENGTH_REQUIRED = 411; /** 412 Precondition Failed (HTTP/1.1 - RFC 2616) */ public static final int SC_PRECONDITION_FAILED = 412; /** 413 Request Entity Too Large (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TOO_LONG = 413; /** 414 Request-URI Too Long (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** 415 Unsupported Media Type (HTTP/1.1 - RFC 2616) */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** 416 Requested Range Not Satisfiable (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** 417 Expectation Failed (HTTP/1.1 - RFC 2616) */ public static final int SC_EXPECTATION_FAILED = 417; /** * Static constant for a 418 error. * 418 Unprocessable Entity (WebDAV drafts?) * or 418 Reauthentication Required (HTTP/1.1 drafts?) */ // not used // public static final int SC_UNPROCESSABLE_ENTITY = 418; /** * Static constant for a 419 error. * 419 Insufficient Space on Resource * (WebDAV - draft-ietf-webdav-protocol-05?) * or 419 Proxy Reauthentication Required * (HTTP/1.1 drafts?) */ public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; /** * Static constant for a 420 error. * 420 Method Failure * (WebDAV - draft-ietf-webdav-protocol-05?) */ public static final int SC_METHOD_FAILURE = 420; /** 422 Unprocessable Entity (WebDAV - RFC 2518) */ public static final int SC_UNPROCESSABLE_ENTITY = 422; /** 423 Locked (WebDAV - RFC 2518) */ public static final int SC_LOCKED = 423; /** 424 Failed Dependency (WebDAV - RFC 2518) */ public static final int SC_FAILED_DEPENDENCY = 424; // --- 5xx Server Error --- /** 500 Server Error (HTTP/1.0 - RFC 1945) */ public static final int SC_INTERNAL_SERVER_ERROR = 500; /** 501 Not Implemented (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_IMPLEMENTED = 501; /** 502 Bad Gateway (HTTP/1.0 - RFC 1945) */ public static final int SC_BAD_GATEWAY = 502; /** 503 Service Unavailable (HTTP/1.0 - RFC 1945) */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** 504 Gateway Timeout (HTTP/1.1 - RFC 2616) */ public static final int SC_GATEWAY_TIMEOUT = 504; /** 505 HTTP Version Not Supported (HTTP/1.1 - RFC 2616) */ public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505; /** 507 Insufficient Storage (WebDAV - RFC 2518) */ public static final int SC_INSUFFICIENT_STORAGE = 507; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/ParseException.java0100644 0000000 0000000 00000004054 12276755423 027351 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 null */ public ParseException(final String message) { super(message); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/RequestLine.java0100644 0000000 0000000 00000003223 12276755424 026656 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpResponse.java0100644 0000000 0000000 00000011757 12276755424 027067 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 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 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 * 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 * 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 true), * it must be fully consumed in order to ensure release of resources. * * @param entity the entity to associate with this response, or * null to unset * * @see HttpEntity#isStreaming() * @see org.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 null */ Locale getLocale(); /** * Changes the locale of this response. * * @param loc the new locale */ void setLocale(Locale loc); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/HttpException.java0100644 0000000 0000000 00000004250 12276755424 027215 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 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 Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public HttpException(final String message, final Throwable cause) { super(message); initCause(cause); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/TokenIterator.java0100644 0000000 0000000 00000003702 12276755424 027212 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 true if there is another token, * false otherwise */ 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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/FormattedHeader.java0100644 0000000 0000000 00000004133 12276755424 027455 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import org.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/ContentTooLongException.java0100644 0000000 0000000 00000003221 12276755423 031206 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/MessageConstraintException.java0100644 0000000 0000000 00000003230 12276755423 031723 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import java.io.IOException; /** * Signals a message constraint violation. * * @since 4.3 */ public class MessageConstraintException extends IOException { private static final long serialVersionUID = 6077207720446368695L; /** * Creates a TruncatedChunkException with the specified detail message. * * @param message The exception detail message */ public MessageConstraintException(final String message) { super(message); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/concurrent/0040755 0000000 0000000 00000000000 12276755424 025740 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/concurrent/Cancellable.java0100644 0000000 0000000 00000002557 12276755424 030776 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.concurrent; /** * A Cancellable represents a process or an operation that can be * canceled. * * @since 4.2 */ public interface Cancellable { boolean cancel(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/concurrent/BasicFuture.java0100644 0000000 0000000 00000011241 12276755424 031013 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.concurrent; import org.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. 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; } public boolean isCancelled() { return this.cancelled; } public boolean isDone() { return this.completed; } private T getResult() throws ExecutionException { if (this.ex != null) { throw new ExecutionException(this.ex); } return this.result; } public synchronized T get() throws InterruptedException, ExecutionException { while (!this.completed) { wait(); } return getResult(); } 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; } 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; } public boolean cancel() { return cancel(true); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/concurrent/FutureCallback.java0100644 0000000 0000000 00000003003 12276755424 031463 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/concurrent/package-info.java0100644 0000000 0000000 00000002347 12276755424 031132 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.concurrent; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/0040755 0000000 0000000 00000000000 12276755424 025072 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/ContentProducer.java0100644 0000000 0000000 00000002777 12276755424 031065 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/BufferedHttpEntity.java0100644 0000000 0000000 00000007237 12276755424 031522 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.HttpEntity; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; import org.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 false */ @Override public boolean isChunked() { return (buffer == null) && super.isChunked(); } /** * Tells that this entity is repeatable. * * @return 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 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/StringEntity.java0100644 0000000 0000000 00000015536 12276755424 030407 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.annotation.NotThreadSafe; import org.apache.http.protocol.HTTP; import org.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; } try { this.content = string.getBytes(charset.name()); } catch (final UnsupportedEncodingException ex) { // should never happen throw new UnsupportedCharsetException(charset.name()); } 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); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.content.length; } public InputStream getContent() throws IOException { return new ByteArrayInputStream(this.content); } 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 false */ public boolean isStreaming() { return false; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } // class StringEntity httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/ContentType.java0100644 0000000 0000000 00000026730 12276755424 030216 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.Serializable; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.Locale; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.annotation.Immutable; import org.apache.http.message.BasicHeaderValueFormatter; import org.apache.http.message.BasicHeaderValueParser; import org.apache.http.message.ParserCursor; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; import org.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 <">, <;>, <,> 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 NameValuePair[] params) throws UnsupportedCharsetException { this.mimeType = mimeType; this.params = params; final String s = getParameter("charset"); this.charset = !TextUtils.isBlank(s) ? Charset.forName(s) : null; } 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 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 null or empty. It may not contain * characters <">, <;>, <,> 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.US); 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 null or empty. It may not contain * characters <">, <;>, <,> 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 null or empty. It may not contain * characters <">, <;>, <,> reserved by the HTTP specification. * @param charset charset. It may not contain characters <">, <;>, <,> 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 String mimeType = helem.getName(); final NameValuePair[] params = helem.getParameters(); return new ContentType(mimeType, params != null && params.length > 0 ? params : null); } /** * Parses textual representation of Content-Type value. * * @param s text * @return content type * @throws ParseException if the given text does not represent a valid * 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]); } else { throw new ParseException("Invalid content type: " + s); } } /** * Extracts Content-Type value from {@link HttpEntity} exactly as * specified by the Content-Type header of the entity. Returns null * if not specified. * * @param entity HTTP entity * @return content type * @throws ParseException if the given text does not represent a valid * 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]); } } return null; } /** * Extracts 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 * 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; } /** * 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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/InputStreamEntity.java0100644 0000000 0000000 00000012110 12276755424 031375 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.annotation.NotThreadSafe; import org.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()); } } public boolean isRepeatable() { return false; } /** * @return the content length or {@code -1} if unknown */ public long getContentLength() { return this.length; } 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). * */ 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(); } } public boolean isStreaming() { return true; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/BasicHttpEntity.java0100644 0000000 0000000 00000007233 12276755424 031015 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; import org.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; } 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 */ 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 false */ 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; } 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(); } } public boolean isStreaming() { return this.content != null; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/ContentLengthStrategy.java0100644 0000000 0000000 00000004103 12276755424 032227 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import org.apache.http.HttpException; import org.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/AbstractHttpEntity.java0100644 0000000 0000000 00000013557 12276755424 031545 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.message.BasicHeader; import org.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 * null, null and 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 null */ 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 null */ 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 */ 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 * 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 * 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 * 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 * 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. */ @Deprecated public void consumeContent() throws IOException { } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/SerializableEntity.java0100644 0000000 0000000 00000007507 12276755424 031546 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.annotation.NotThreadSafe; import org.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(); } public InputStream getContent() throws IOException, IllegalStateException { if (this.objSer == null) { createBytes(this.objRef); } return new ByteArrayInputStream(this.objSer); } public long getContentLength() { if (this.objSer == null) { return -1; } else { return this.objSer.length; } } public boolean isRepeatable() { return true; } public boolean isStreaming() { return this.objSer == null; } 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(); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/ByteArrayEntity.java0100644 0000000 0000000 00000007374 12276755424 031044 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.annotation.NotThreadSafe; import org.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); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.len; } public InputStream getContent() { return new ByteArrayInputStream(this.b, this.off, this.len); } 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 false */ public boolean isStreaming() { return false; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } // class ByteArrayEntity httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/EntityTemplate.java0100644 0000000 0000000 00000004545 12276755424 030712 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.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"); } public long getContentLength() { return -1; } public InputStream getContent() throws IOException { final ByteArrayOutputStream buf = new ByteArrayOutputStream(); writeTo(buf); return new ByteArrayInputStream(buf.toByteArray()); } public boolean isRepeatable() { return true; } public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); this.contentproducer.writeTo(outstream); } public boolean isStreaming() { return false; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/package-info.java0100644 0000000 0000000 00000002356 12276755424 030264 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.entity; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/HttpEntityWrapper.java0100644 0000000 0000000 00000006275 12276755424 031421 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.annotation.NotThreadSafe; import org.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 public boolean isRepeatable() { return wrappedEntity.isRepeatable(); } public boolean isChunked() { return wrappedEntity.isChunked(); } public long getContentLength() { return wrappedEntity.getContentLength(); } public Header getContentType() { return wrappedEntity.getContentType(); } public Header getContentEncoding() { return wrappedEntity.getContentEncoding(); } public InputStream getContent() throws IOException { return wrappedEntity.getContent(); } public void writeTo(final OutputStream outstream) throws IOException { wrappedEntity.writeTo(outstream); } 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. */ @Deprecated public void consumeContent() throws IOException { wrappedEntity.consumeContent(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/entity/FileEntity.java0100644 0000000 0000000 00000006661 12276755424 030017 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.annotation.NotThreadSafe; import org.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"); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.file.length(); } public InputStream getContent() throws IOException { return new FileInputStream(this.file); } 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 false */ 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 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/0040755 0000000 0000000 00000000000 12276755423 025040 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/BasicHttpParams.java0100644 0000000 0000000 00000013306 12276755423 030730 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; import java.io.Serializable; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.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 'org.apache.http.config' * and 'org.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(); } public Object getParameter(final String name) { return this.parameters.get(name); } 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; } 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 */ 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 * @since 4.2 */ @Override public Set getNames() { return new HashSet(this.parameters.keySet()); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/HttpParamConfig.java0100644 0000000 0000000 00000006533 12276755423 030735 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.MessageConstraints; import org.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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/CoreProtocolPNames.java0100644 0000000 0000000 00000012331 12276755423 031416 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; /** * Defines parameter names for protocol execution in HttpCore. * * @since 4.0 * * @deprecated (4.3) use configuration classes provided 'org.apache.http.config' * and 'org.apache.http.client.config' */ @Deprecated public interface CoreProtocolPNames { /** * Defines the {@link org.apache.http.ProtocolVersion} used per default. *

* This parameter expects a value of type {@link org.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 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 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 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"; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/HttpParamsNames.java0100644 0000000 0000000 00000003521 12276755423 030750 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 'org.apache.http.config' * and 'org.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 */ Set getNames(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/package-info.java0100644 0000000 0000000 00000002356 12276755423 030232 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.params; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/HttpParams.java0100644 0000000 0000000 00000014742 12276755423 027773 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 'org.apache.http.config' * and 'org.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, * null if the parameter is not set or if it * is explicitly set to 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 true. * * @param name parameter name * * @return true if the parameter is set to value true, * false if it is not set or set to false */ boolean isParameterTrue(String name); /** * Checks if a boolean parameter is not set or false. * * @param name parameter name * * @return true if the parameter is either not set or * set to value false, * false if it is set to true */ boolean isParameterFalse(String name); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/AbstractHttpParams.java0100644 0000000 0000000 00000007564 12276755423 031463 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 'org.apache.http.config' * and 'org.apache.http.client.config' */ @Deprecated public abstract class AbstractHttpParams implements HttpParams, HttpParamsNames { /** * Instantiates parameters. */ protected AbstractHttpParams() { super(); } public long getLongParameter(final String name, final long defaultValue) { final Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Long) param).longValue(); } public HttpParams setLongParameter(final String name, final long value) { setParameter(name, Long.valueOf(value)); return this; } public int getIntParameter(final String name, final int defaultValue) { final Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Integer) param).intValue(); } public HttpParams setIntParameter(final String name, final int value) { setParameter(name, Integer.valueOf(value)); return this; } public double getDoubleParameter(final String name, final double defaultValue) { final Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Double) param).doubleValue(); } public HttpParams setDoubleParameter(final String name, final double value) { setParameter(name, Double.valueOf(value)); return this; } public boolean getBooleanParameter(final String name, final boolean defaultValue) { final Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Boolean) param).booleanValue(); } public HttpParams setBooleanParameter(final String name, final boolean value) { setParameter(name, value ? Boolean.TRUE : Boolean.FALSE); return this; } public boolean isParameterTrue(final String name) { return getBooleanParameter(name, false); } public boolean isParameterFalse(final String name) { return !getBooleanParameter(name, false); } /** * {@inheritDoc} *

* Dummy implementation - must be overridden by subclasses. * * @since 4.2 * @throws UnsupportedOperationException - always */ public Set getNames(){ throw new UnsupportedOperationException(); } } // class AbstractHttpParams httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/params/CoreConnectionPNames.java0100644 0000000 0000000 00000015056 12276755423 031723 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.params; /** * Defines parameter names for connections in HttpCore. * * @since 4.0 * * @deprecated (4.3) use configuration classes provided 'org.apache.http.config' * and 'org.apache.http.client.config' */ @Deprecated public interface CoreConnectionPNames { /** * Defines the socket timeout (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 0 implies that * the option is disabled. Value -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"; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/0040755 0000000 0000000 00000000000 12276755425 024520 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/BHttpConnectionBase.java0100644 0000000 0000000 00000033615 12276755425 031224 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.Header; import org.apache.http.HttpConnection; import org.apache.http.HttpConnectionMetrics; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpInetConnection; import org.apache.http.HttpMessage; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.io.ChunkedInputStream; import org.apache.http.impl.io.ChunkedOutputStream; import org.apache.http.impl.io.ContentLengthInputStream; import org.apache.http.impl.io.ContentLengthOutputStream; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.io.IdentityInputStream; import org.apache.http.impl.io.IdentityOutputStream; import org.apache.http.impl.io.SessionInputBufferImpl; import org.apache.http.impl.io.SessionOutputBufferImpl; import org.apache.http.io.SessionInputBuffer; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; import org.apache.http.util.Asserts; import org.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 HttpConnectionMetricsImpl connMetrics; private final ContentLengthStrategy incomingContentStrategy; private final ContentLengthStrategy outgoingContentStrategy; private volatile boolean open; private volatile Socket socket; /** * 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 null simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If null simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If null * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If null * {@link LaxContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If null * {@link StrictContentLengthStrategy#INSTANCE} will be used. */ protected BHttpConnectionBase( final int buffersize, final int fragmentSizeHint, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints, 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, constraints != null ? constraints : MessageConstraints.DEFAULT, chardecoder); this.outbuffer = new SessionOutputBufferImpl(outTransportMetrics, buffersize, fragmentSizeHint, charencoder); this.connMetrics = new HttpConnectionMetricsImpl(inTransportMetrics, outTransportMetrics); this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy : LaxContentLengthStrategy.INSTANCE; this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy : StrictContentLengthStrategy.INSTANCE; } protected void ensureOpen() throws IOException { Asserts.check(this.open, "Connection is not open"); if (!this.inbuffer.isBound()) { this.inbuffer.bind(getSocketInputStream(this.socket)); } if (!this.outbuffer.isBound()) { this.outbuffer.bind(getSocketOutputStream(this.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 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.socket = socket; this.open = true; 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(); } public boolean isOpen() { return this.open; } protected Socket getSocket() { return this.socket; } 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); } else if (len == ContentLengthStrategy.IDENTITY) { return new IdentityInputStream(inbuffer); } 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; } 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) { 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 { this.inbuffer.clear(); this.outbuffer.flush(); 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 int fillInputBuffer(final int timeout) throws IOException { final int oldtimeout = this.socket.getSoTimeout(); try { this.socket.setSoTimeout(timeout); return this.inbuffer.fillBuffer(); } finally { this.socket.setSoTimeout(oldtimeout); } } protected boolean awaitInput(final int timeout) throws IOException { if (this.inbuffer.hasBufferedData()) { return true; } fillInputBuffer(timeout); return this.inbuffer.hasBufferedData(); } 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(); } public HttpConnectionMetrics getMetrics() { return this.connMetrics; } @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) { NetUtils.formatAddress(buffer, localAddress); buffer.append("<->"); NetUtils.formatAddress(buffer, remoteAddress); } return buffer.toString(); } else { return "[Not bound]"; } } } ././@LongLink0100644 0000000 0000000 00000000145 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/NoConnectionReuseStrategy.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/NoConnectionReuseStrategy.java0100644 0000000 0000000 00000003446 12276755425 032512 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpResponse; import org.apache.http.annotation.Immutable; import org.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(); } public boolean keepAlive(final HttpResponse response, final HttpContext context) { return false; } } ././@LongLink0100644 0000000 0000000 00000000152 12276757360 011650 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategy.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategy0100644 0000000 0000000 00000020055 12276755425 032575 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ParseException; import org.apache.http.ProtocolVersion; import org.apache.http.TokenIterator; import org.apache.http.annotation.Immutable; import org.apache.http.message.BasicTokenIterator; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.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 Connection header will * be examined. In the absence of a Connection header, the * non-standard but commonly used Proxy-Connection header takes * it's role. A token close indicates that the connection cannot * be reused. If there is no such token, a token keep-alive * indicates that the connection should be re-used. If neither token is found, * or if there are no Connection headers, the default policy for * the HTTP version is applied. Since HTTP/1.1, connections are * re-used by default. Up until 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 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; } } ././@LongLink0100644 0000000 0000000 00000000150 12276757360 011646 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpClientConnection.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpClientConnection.j0100644 0000000 0000000 00000016473 12276755425 032410 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.HttpClientConnection; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.io.DefaultHttpRequestWriterFactory; import org.apache.http.impl.io.DefaultHttpResponseParserFactory; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.HttpMessageParserFactory; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.HttpMessageWriterFactory; import org.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 null simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If null simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If null * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If null * {@link org.apache.http.impl.entity.LaxContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If null * {@link org.apache.http.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used. * @param requestWriterFactory request writer factory. If null * {@link DefaultHttpRequestWriterFactory#INSTANCE} will be used. * @param responseParserFactory response parser factory. If 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); } public boolean isResponseAvailable(final int timeout) throws IOException { ensureOpen(); try { return awaitInput(timeout); } catch (final SocketTimeoutException ex) { return false; } } public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException { Args.notNull(request, "HTTP request"); ensureOpen(); this.requestWriter.write(request); onRequestSubmitted(request); incrementRequestCount(); } 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(); } 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; } public void receiveResponseEntity( final HttpResponse response) throws HttpException, IOException { Args.notNull(response, "HTTP response"); ensureOpen(); final HttpEntity entity = prepareInput(response); response.setEntity(entity); } public void flush() throws IOException { ensureOpen(); doFlush(); } } ././@LongLink0100644 0000000 0000000 00000000145 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/HttpConnectionMetricsImpl.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/HttpConnectionMetricsImpl.java0100644 0000000 0000000 00000011472 12276755425 032475 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpConnectionMetrics; import org.apache.http.annotation.NotThreadSafe; import org.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 -------------------------- */ public long getReceivedBytesCount() { if (this.inTransportMetric != null) { return this.inTransportMetric.getBytesTransferred(); } else { return -1; } } public long getSentBytesCount() { if (this.outTransportMetric != null) { return this.outTransportMetric.getBytesTransferred(); } else { return -1; } } public long getRequestCount() { return this.requestCount; } public void incrementRequestCount() { this.requestCount++; } public long getResponseCount() { return this.responseCount; } public void incrementResponseCount() { this.responseCount++; } 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); } 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; } } ././@LongLink0100644 0000000 0000000 00000000146 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/EnglishReasonPhraseCatalog.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/EnglishReasonPhraseCatalog.jav0100644 0000000 0000000 00000020022 12276755425 032412 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.util.Locale; import org.apache.http.HttpStatus; import org.apache.http.ReasonPhraseCatalog; import org.apache.http.annotation.Immutable; import org.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 null */ 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"); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/ConnSupport.java0100644 0000000 0000000 00000005515 12276755425 027660 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.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; } } } ././@LongLink0100644 0000000 0000000 00000000157 12276757360 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpServerConnectionFactory.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpServerConnectionFa0100644 0000000 0000000 00000010323 12276755425 032443 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.annotation.Immutable; import org.apache.http.config.ConnectionConfig; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.io.HttpMessageParserFactory; import org.apache.http.io.HttpMessageWriterFactory; import java.io.IOException; import java.net.Socket; /** * Default factory for {@link org.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); } 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; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/package-info.java0100644 0000000 0000000 00000002442 12276755425 027706 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.impl; ././@LongLink0100644 0000000 0000000 00000000145 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultHttpRequestFactory.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultHttpRequestFactory.java0100644 0000000 0000000 00000007406 12276755425 032514 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.MethodNotSupportedException; import org.apache.http.RequestLine; import org.apache.http.annotation.Immutable; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.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; } 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"); } } 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"); } } } ././@LongLink0100644 0000000 0000000 00000000146 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultHttpResponseFactory.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultHttpResponseFactory.jav0100644 0000000 0000000 00000007534 12276755425 032523 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.util.Locale; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.ProtocolVersion; import org.apache.http.ReasonPhraseCatalog; import org.apache.http.StatusLine; import org.apache.http.annotation.Immutable; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import org.apache.http.protocol.HttpContext; import org.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 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 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 * null to use the default locale * * @return the locale for the response, never null */ protected Locale determineLocale(final HttpContext context) { return Locale.getDefault(); } } ././@LongLink0100644 0000000 0000000 00000000150 12276757360 011646 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpServerConnection.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpServerConnection.j0100644 0000000 0000000 00000016227 12276755425 032435 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.entity.DisallowIdentityContentLengthStrategy; import org.apache.http.impl.io.DefaultHttpRequestParserFactory; import org.apache.http.impl.io.DefaultHttpResponseWriterFactory; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.HttpMessageParserFactory; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.HttpMessageWriterFactory; import org.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 null simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If null simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If null * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If null * {@link DisallowIdentityContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If null * {@link org.apache.http.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used. * @param requestParserFactory request parser factory. If null * {@link DefaultHttpRequestParserFactory#INSTANCE} will be used. * @param responseWriterFactory response writer factory. If 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); } public HttpRequest receiveRequestHeader() throws HttpException, IOException { ensureOpen(); final HttpRequest request = this.requestParser.parse(); onRequestReceived(request); incrementRequestCount(); return request; } public void receiveRequestEntity(final HttpEntityEnclosingRequest request) throws HttpException, IOException { Args.notNull(request, "HTTP request"); ensureOpen(); final HttpEntity entity = prepareInput(request); request.setEntity(entity); } 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(); } } 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(); } public void flush() throws IOException { ensureOpen(); doFlush(); } } ././@LongLink0100644 0000000 0000000 00000000157 12276757360 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpClientConnectionFactory.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpClientConnectionFa0100644 0000000 0000000 00000010323 12276755425 032413 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.annotation.Immutable; import org.apache.http.config.ConnectionConfig; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.io.HttpMessageParserFactory; import org.apache.http.io.HttpMessageWriterFactory; import java.io.IOException; import java.net.Socket; /** * Default factory for {@link org.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); } 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; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/entity/0040755 0000000 0000000 00000000000 12276755425 026034 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000170 12276757360 011650 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/entity/DisallowIdentityContent0100644 0000000 0000000 00000004605 12276755425 032604 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.ProtocolException; import org.apache.http.annotation.Immutable; import org.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; } 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; } } ././@LongLink0100644 0000000 0000000 00000000153 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/entity/LaxContentLengthStrategy.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/entity/LaxContentLengthStrateg0100644 0000000 0000000 00000011342 12276755425 032530 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.ParseException; import org.apache.http.ProtocolException; import org.apache.http.annotation.Immutable; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; /** * The lax implementation of the content length strategy. This class will ignore * unrecognized transfer encodings and malformed 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 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 LaxContentLengthStrategy instance. {@link ContentLengthStrategy#IDENTITY} * is used per default when content length is not explicitly specified in the message. */ public LaxContentLengthStrategy() { this(IDENTITY); } 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; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/entity/package-info.java0100644 0000000 0000000 00000002407 12276755425 031223 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.impl.entity; ././@LongLink0100644 0000000 0000000 00000000156 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/entity/StrictContentLengthStrategy.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/entity/StrictContentLengthStra0100644 0000000 0000000 00000010752 12276755425 032560 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.annotation.Immutable; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.protocol.HTTP; import org.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 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 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 StrictContentLengthStrategy instance. {@link ContentLengthStrategy#IDENTITY} * is used per default when content length is not explicitly specified in the message. */ public StrictContentLengthStrategy() { this(IDENTITY); } 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; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/0040755 0000000 0000000 00000000000 12276755425 025127 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000146 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/SessionOutputBufferImpl.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/SessionOutputBufferImpl.jav0100644 0000000 0000000 00000022254 12276755425 032453 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.BufferInfo; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; import org.apache.http.util.Asserts; import org.apache.http.util.ByteArrayBuffer; import org.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 0 disables fragment buffering. * @param charencoder charencoder to be used for encoding HTTP protocol elements. * If 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; } public int capacity() { return this.buffer.capacity(); } public int length() { return this.buffer.length(); } 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); } } public void flush() throws IOException { flushBuffer(); flushStream(); } 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); } } 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.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. */ 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. */ 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(); } public HttpTransportMetrics getMetrics() { return this.metrics; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/ChunkedOutputStream.java0100644 0000000 0000000 00000015404 12276755425 031751 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.io.OutputStream; import org.apache.http.annotation.NotThreadSafe; import org.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(); } } } ././@LongLink0100644 0000000 0000000 00000000156 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriterFactory.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriterFac0100644 0000000 0000000 00000004414 12276755425 032456 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import org.apache.http.HttpRequest; import org.apache.http.annotation.Immutable; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.HttpMessageWriterFactory; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.message.BasicLineFormatter; import org.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); } public HttpMessageWriter create(final SessionOutputBuffer buffer) { return new DefaultHttpRequestWriter(buffer, lineFormatter); } } ././@LongLink0100644 0000000 0000000 00000000150 12276757360 011646 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/ContentLengthOutputStream.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/ContentLengthOutputStream.j0100644 0000000 0000000 00000010377 12276755425 032460 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.io.OutputStream; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.SessionOutputBuffer; import org.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 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++; } } } ././@LongLink0100644 0000000 0000000 00000000157 12276757360 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriterFactory.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriterFa0100644 0000000 0000000 00000004426 12276755425 032464 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import org.apache.http.HttpResponse; import org.apache.http.annotation.Immutable; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.HttpMessageWriterFactory; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.message.BasicLineFormatter; import org.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); } public HttpMessageWriter create(final SessionOutputBuffer buffer) { return new DefaultHttpResponseWriter(buffer, lineFormatter); } } ././@LongLink0100644 0000000 0000000 00000000157 12276757360 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParserFactory.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParserFa0100644 0000000 0000000 00000005315 12276755425 032442 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.annotation.Immutable; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.HttpMessageParserFactory; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.BasicLineParser; import org.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); } public HttpMessageParser create(final SessionInputBuffer buffer, final MessageConstraints constraints) { return new DefaultHttpResponseParser(buffer, lineParser, responseFactory, constraints); } } ././@LongLink0100644 0000000 0000000 00000000150 12276757360 011646 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParser.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParser.j0100644 0000000 0000000 00000012173 12276755425 032423 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.NoHttpResponseException; import org.apache.http.ParseException; import org.apache.http.StatusLine; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.LineParser; import org.apache.http.message.ParserCursor; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.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 null * {@link org.apache.http.message.BasicLineParser#INSTANCE} will be used * @param responseFactory the response factory. If null * {@link DefaultHttpResponseFactory#INSTANCE} will be used. * @param constraints the message constraints. If 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); } } ././@LongLink0100644 0000000 0000000 00000000147 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParser.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParser.ja0100644 0000000 0000000 00000012037 12276755425 032415 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.ParseException; import org.apache.http.RequestLine; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.LineParser; import org.apache.http.message.ParserCursor; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.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 null * {@link org.apache.http.message.BasicLineParser#INSTANCE} will be used. * @param requestFactory the response factory. If null * {@link DefaultHttpRequestFactory#INSTANCE} will be used. * @param constraints the message constraints. If 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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/IdentityOutputStream.java0100644 0000000 0000000 00000006250 12276755425 032160 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.io.OutputStream; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.SessionOutputBuffer; import org.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); } } ././@LongLink0100644 0000000 0000000 00000000147 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriter.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriter.ja0100644 0000000 0000000 00000004614 12276755425 032437 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.HttpRequest; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.SessionOutputBuffer; import org.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 null * {@link org.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/AbstractMessageWriter.java0100644 0000000 0000000 00000010622 12276755425 032235 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.message.BasicLineFormatter; import org.apache.http.message.LineFormatter; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.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 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; 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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/package-info.java0100644 0000000 0000000 00000002457 12276755425 030323 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.impl.io; ././@LongLink0100644 0000000 0000000 00000000156 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParserFactory.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParserFac0100644 0000000 0000000 00000005270 12276755425 032437 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.annotation.Immutable; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.HttpMessageParserFactory; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.BasicLineParser; import org.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); } public HttpMessageParser create(final SessionInputBuffer buffer, final MessageConstraints constraints) { return new DefaultHttpRequestParser(buffer, lineParser, requestFactory, constraints); } } ././@LongLink0100644 0000000 0000000 00000000145 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/SessionInputBufferImpl.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/SessionInputBufferImpl.java0100644 0000000 0000000 00000033731 12276755425 032415 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.MessageConstraintException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.io.BufferInfo; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.io.SessionInputBuffer; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; import org.apache.http.util.Asserts; import org.apache.http.util.ByteArrayBuffer; import org.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 null * {@link MessageConstraints#DEFAULT} will be used. * @param chardecoder chardecoder to be used for decoding HTTP protocol elements. * If 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; } public int capacity() { return this.buffer.length; } public int length() { return this.bufferlen - this.bufferpos; } 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; } 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 = 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; } } 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 -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; } } final int maxLineLen = this.constraints.getMaxLineLength(); if (maxLineLen > 0 && this.linebuffer.length() >= maxLineLen) { throw new MessageConstraintException("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, * 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; } 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 boolean isDataAvailable(final int timeout) throws IOException { return hasBufferedData(); } public HttpTransportMetrics getMetrics() { return this.metrics; } } ././@LongLink0100644 0000000 0000000 00000000150 12276757360 011646 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriter.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriter.j0100644 0000000 0000000 00000004622 12276755425 032443 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.SessionOutputBuffer; import org.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 null * {@link org.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); } } ././@LongLink0100644 0000000 0000000 00000000147 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/HttpTransportMetricsImpl.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/HttpTransportMetricsImpl.ja0100644 0000000 0000000 00000003647 12276755425 032457 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import org.apache.http.annotation.NotThreadSafe; import org.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(); } public long getBytesTransferred() { return this.bytesTransferred; } public void setBytesTransferred(final long count) { this.bytesTransferred = count; } public void incrementBytesTransferred(final long count) { this.bytesTransferred += count; } public void reset() { this.bytesTransferred = 0; } } ././@LongLink0100644 0000000 0000000 00000000147 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/ContentLengthInputStream.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/ContentLengthInputStream.ja0100644 0000000 0000000 00000017342 12276755425 032417 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.io.InputStream; import org.apache.http.ConnectionClosedException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.BufferInfo; import org.apache.http.io.SessionInputBuffer; import org.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 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; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/IdentityInputStream.java0100644 0000000 0000000 00000005761 12276755425 031765 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.io.InputStream; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.BufferInfo; import org.apache.http.io.SessionInputBuffer; import org.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 * -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); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/AbstractMessageParser.java0100644 0000000 0000000 00000026623 12276755425 032225 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.MessageConstraintException; import org.apache.http.ParseException; import org.apache.http.ProtocolException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.BasicLineParser; import org.apache.http.message.LineParser; import org.apache.http.params.HttpParamConfig; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.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 null {@link BasicLineParser#INSTANCE} * will be used. * @param constraints the message constraints. If 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 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; 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"); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/io/ChunkedInputStream.java0100644 0000000 0000000 00000023014 12276755425 031544 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.io.InputStream; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.MalformedChunkCodingException; import org.apache.http.TruncatedChunkException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.BufferInfo; import org.apache.http.io.SessionInputBuffer; import org.apache.http.util.Args; import org.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 BUFFER_SIZE = 2048; /** The session input buffer */ private final SessionInputBuffer in; private final CharArrayBuffer buffer; 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 */ public ChunkedInputStream(final SessionInputBuffer in) { super(); this.in = Args.notNull(in, "Session input buffer"); this.pos = 0; this.buffer = new CharArrayBuffer(16); this.state = CHUNK_LEN; } @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 { chunkSize = getChunkSize(); if (chunkSize < 0) { throw new MalformedChunkCodingException("Negative chunk size"); } state = CHUNK_DATA; pos = 0; if (chunkSize == 0) { eof = true; parseTrailerHeaders(); } } /** * 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) { return 0; } 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) { return 0; } 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, -1, -1, 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) { // 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/pool/0040755 0000000 0000000 00000000000 12276755425 025471 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/pool/BasicConnPool.java0100644 0000000 0000000 00000006142 12276755425 031025 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.pool; import java.util.concurrent.atomic.AtomicLong; import org.apache.http.HttpClientConnection; import org.apache.http.HttpHost; import org.apache.http.annotation.ThreadSafe; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.SocketConfig; import org.apache.http.params.HttpParams; import org.apache.http.pool.AbstractConnPool; import org.apache.http.pool.ConnFactory; /** * A very basic {@link org.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/pool/BasicConnFactory.java0100644 0000000 0000000 00000014661 12276755425 031530 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.HttpClientConnection; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpHost; import org.apache.http.annotation.Immutable; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.SocketConfig; import org.apache.http.impl.DefaultBHttpClientConnection; import org.apache.http.impl.DefaultBHttpClientConnectionFactory; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParamConfig; import org.apache.http.params.HttpParams; import org.apache.http.pool.ConnFactory; import org.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; } 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()); socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout); socket.setTcpNoDelay(this.sconfig.isTcpNoDelay()); final int linger = this.sconfig.getSoLinger(); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } socket.setKeepAlive(this.sconfig.isSoKeepAlive()); return this.connFactory.createConnection(socket); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/pool/BasicPoolEntry.java0100644 0000000 0000000 00000004113 12276755425 031225 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.pool; import java.io.IOException; import org.apache.http.HttpClientConnection; import org.apache.http.HttpHost; import org.apache.http.annotation.ThreadSafe; import org.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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/impl/pool/package-info.java0100644 0000000 0000000 00000002463 12276755425 030662 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.impl.pool; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/config/0040755 0000000 0000000 00000000000 12276755423 025022 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/config/MessageConstraints.java0100644 0000000 0000000 00000006720 12276755423 031503 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.config; import org.apache.http.util.Args; /** * HTTP Message constraints: line length and header count. * * @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); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/config/Registry.java0100644 0000000 0000000 00000003576 12276755423 027505 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.config; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.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); } public I lookup(final String key) { if (key == null) { return null; } return map.get(key.toLowerCase(Locale.US)); } @Override public String toString() { return map.toString(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/config/package-info.java0100644 0000000 0000000 00000002345 12276755423 030212 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.config; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/config/Lookup.java0100644 0000000 0000000 00000002501 12276755423 027131 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.config; /** * Generic lookup by low-case string ID. * * @since 4.3 */ public interface Lookup { I lookup(String name); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/config/RegistryBuilder.java0100644 0000000 0000000 00000004113 12276755423 031000 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.config; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.http.annotation.NotThreadSafe; import org.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.US), item); return this; } public Registry build() { return new Registry(items); } @Override public String toString() { return items.toString(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/config/SocketConfig.java0100644 0000000 0000000 00000013500 12276755423 030237 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.config; import org.apache.http.annotation.Immutable; import org.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; SocketConfig( final int soTimeout, final boolean soReuseAddress, final int soLinger, final boolean soKeepAlive, final boolean tcpNoDelay) { super(); this.soTimeout = soTimeout; this.soReuseAddress = soReuseAddress; this.soLinger = soLinger; this.soKeepAlive = soKeepAlive; this.tcpNoDelay = tcpNoDelay; } /** * Determines the default socket timeout value for non-blocking I/O operations. *

* Default: 0 (no timeout) * * @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: false * * @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: -1 * * @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: -1 * * @see java.net.SocketOptions#SO_KEEPALIVE */ public boolean isSoKeepAlive() { return this.soKeepAlive; } /** * Determines the default value of the {@link java.net.SocketOptions#TCP_NODELAY} parameter * for newly created sockets. *

* Default: false * * @see java.net.SocketOptions#TCP_NODELAY */ public boolean isTcpNoDelay() { return tcpNoDelay; } @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("]"); 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()); } public static class Builder { private int soTimeout; private boolean soReuseAddress; private int soLinger; private boolean soKeepAlive; private boolean tcpNoDelay; 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; } public SocketConfig build() { return new SocketConfig(soTimeout, soReuseAddress, soLinger, soKeepAlive, tcpNoDelay); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/config/ConnectionConfig.java0100644 0000000 0000000 00000014772 12276755423 031122 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.config; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import org.apache.http.Consts; import org.apache.http.annotation.Immutable; import org.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); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/0040755 0000000 0000000 00000000000 12276755426 025421 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000150 12276757360 011646 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandlerMapper.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandlerMapper.j0100644 0000000 0000000 00000003425 12276755426 032530 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.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 null if no match * is found. */ HttpRequestHandler lookup(HttpRequest request); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpService.java0100644 0000000 0000000 00000042115 12276755426 030524 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpServerConnection; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.ProtocolException; import org.apache.http.UnsupportedHttpVersionException; import org.apache.http.annotation.Immutable; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.EncodingUtils; import org.apache.http.util.EntityUtils; /** * HttpService is a server side HTTP protocol handler based on * the classic (blocking) I/O model. *

* 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. *

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

* 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 null * {@link DefaultConnectionReuseStrategy#INSTANCE} will be used. * @param responseFactory the response factory. If 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 null * {@link DefaultConnectionReuseStrategy#INSTANCE} will be used. * @param responseFactory the response factory. If 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); HttpResponse response = null; try { final HttpRequest 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); conn.sendResponseEntity(response); conn.flush(); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } } /** * 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; } public HttpRequestHandler lookup(final HttpRequest request) { return resolver.lookup(request.getRequestLine().getUri()); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/ResponseContent.java0100644 0000000 0000000 00000012647 12276755426 031424 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * ResponseContent is the most important interceptor for outgoing responses. * It is responsible for delimiting content length by adding * Content-Length or 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 Content-Length or 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 true the Content-Length and * Transfer-Encoding headers will be created or updated if already present. * If set to false the Content-Length and * 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. */ 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"); } } } } ././@LongLink0100644 0000000 0000000 00000000153 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpResponseInterceptorList.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpResponseInterceptorLis0100644 0000000 0000000 00000006473 12276755426 032700 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.util.List; import org.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 * 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); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/ResponseServer.java0100644 0000000 0000000 00000004444 12276755426 031254 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * ResponseServer is responsible for adding 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); } 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); } } } } ././@LongLink0100644 0000000 0000000 00000000145 12276757360 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/RequestExpectContinue.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/RequestExpectContinue.java0100644 0000000 0000000 00000006663 12276755426 032602 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.apache.http.annotation.Immutable; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.util.Args; /** * RequestExpectContinue is responsible for enabling the 'expect-continue' * handshake by adding 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 org.apache.http.protocol.RequestExpectContinue#RequestExpectContinue(boolean)} */ @Deprecated public RequestExpectContinue() { this(false); } /** * @since 4.3 */ public RequestExpectContinue(final boolean activeByDefault) { super(); this.activeByDefault = activeByDefault; } 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); } } } } } } ././@LongLink0100644 0000000 0000000 00000000152 12276757360 011650 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandlerResolver.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandlerResolver0100644 0000000 0000000 00000003503 12276755426 032652 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 null if no match * is found. */ HttpRequestHandler lookup(String requestURI); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/RequestContent.java0100644 0000000 0000000 00000012222 12276755426 031243 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * RequestContent is the most important interceptor for outgoing requests. * It is responsible for delimiting content length by adding * Content-Length or 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 Content-Length or 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 true the Content-Length and * Transfer-Encoding headers will be created or updated if already present. * If set to false the Content-Length and * 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; } 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()); } } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpRequestExecutor.java0100644 0000000 0000000 00000027571 12276755426 032304 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpClientConnection; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * HttpRequestExecutor is a client side HTTP protocol handler based * on the blocking (classic) I/O model. *

* 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 * 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 * 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 org.apache.http.util.EntityUtils#consume(org.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 ././@LongLink0100644 0000000 0000000 00000000147 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpExpectationVerifier.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpExpectationVerifier.ja0100644 0000000 0000000 00000006277 12276755426 032565 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.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 * 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 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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpContext.java0100644 0000000 0000000 00000005317 12276755426 030553 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 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 null if not set. */ Object removeAttribute(String id); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandler.java0100644 0000000 0000000 00000004532 12276755426 032053 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpCoreContext.java0100644 0000000 0000000 00000011415 12276755426 031360 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.apache.http.HttpConnection; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.annotation.NotThreadSafe; import org.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 org.apache.http.HttpConnection} object that * represents the actual HTTP connection. */ public static final String HTTP_CONNECTION = "http.connection"; /** * Attribute name of a {@link org.apache.http.HttpRequest} object that * represents the actual HTTP request. */ public static final String HTTP_REQUEST = "http.request"; /** * Attribute name of a {@link org.apache.http.HttpResponse} object that * represents the actual HTTP response. */ public static final String HTTP_RESPONSE = "http.response"; /** * Attribute name of a {@link org.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(); } public Object getAttribute(final String id) { return context.getAttribute(id); } public void setAttribute(final String id, final Object obj) { context.setAttribute(id, obj); } 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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/RequestTargetHost.java0100644 0000000 0000000 00000007161 12276755426 031723 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import java.net.InetAddress; import org.apache.http.HttpConnection; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpInetConnection; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * RequestTargetHost is responsible for adding Host header. This * interceptor is required for client side protocol processors. * * @since 4.0 */ @Immutable public class RequestTargetHost implements HttpRequestInterceptor { public RequestTargetHost() { super(); } 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()); } } } ././@LongLink0100644 0000000 0000000 00000000146 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/ImmutableHttpProcessor.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/ImmutableHttpProcessor.jav0100644 0000000 0000000 00000013001 12276755426 032572 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import java.util.List; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.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); } public void process( final HttpRequest request, final HttpContext context) throws IOException, HttpException { for (final HttpRequestInterceptor requestInterceptor : this.requestInterceptors) { requestInterceptor.process(request, context); } } public void process( final HttpResponse response, final HttpContext context) throws IOException, HttpException { for (final HttpResponseInterceptor responseInterceptor : this.responseInterceptors) { responseInterceptor.process(response, context); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/package-info.java0100644 0000000 0000000 00000002474 12276755426 030614 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.protocol; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/ResponseDate.java0100644 0000000 0000000 00000004530 12276755426 030657 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.annotation.ThreadSafe; import org.apache.http.util.Args; /** * ResponseDate is responsible for adding 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(); } 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); } } } ././@LongLink0100644 0000000 0000000 00000000152 12276757360 011650 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpRequestInterceptorList.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpRequestInterceptorList0100644 0000000 0000000 00000006442 12276755426 032712 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.util.List; import org.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 * 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); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/BasicHttpContext.java0100644 0000000 0000000 00000005325 12276755426 031514 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.http.annotation.ThreadSafe; import org.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; } 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; } 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); } } 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/ResponseConnControl.java0100644 0000000 0000000 00000010420 12276755426 032233 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * ResponseConnControl is responsible for adding Connection header * to the outgoing responses, which is essential for managing persistence of * 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(); } 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); } } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpDateGenerator.java0100644 0000000 0000000 00000005023 12276755426 031645 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.apache.http.annotation.GuardedBy; import org.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; } } ././@LongLink0100644 0000000 0000000 00000000153 12276757360 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/UriHttpRequestHandlerMapper.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/UriHttpRequestHandlerMappe0100644 0000000 0000000 00000007527 12276755426 032605 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.apache.http.HttpRequest; import org.apache.http.annotation.ThreadSafe; import org.apache.http.util.Args; /** * Maintains a map of HTTP request handlers keyed by a request URI pattern. *
* Patterns may have three formats: *

    *
  • *
  • *
  • *<uri>
  • *
  • <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 null if no match is found. */ public HttpRequestHandler lookup(final HttpRequest request) { Args.notNull(request, "HTTP request"); return matcher.lookup(getRequestPath(request)); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/RequestConnControl.java0100644 0000000 0000000 00000004615 12276755426 032076 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * RequestConnControl is responsible for adding Connection header * to the outgoing requests, which is essential for managing persistence of * 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(); } 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); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpProcessorBuilder.java0100644 0000000 0000000 00000011022 12276755426 032403 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.apache.http.HttpRequestInterceptor; import org.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HttpProcessor.java0100644 0000000 0000000 00000004420 12276755426 031100 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.apache.http.HttpRequestInterceptor; import org.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 } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/RequestDate.java0100644 0000000 0000000 00000004461 12276755426 030514 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.annotation.ThreadSafe; import org.apache.http.util.Args; /** * RequestDate interceptor is responsible for adding 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(); } 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); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/UriPatternMatcher.java0100644 0000000 0000000 00000011666 12276755426 031674 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.util.HashMap; import java.util.Map; import org.apache.http.annotation.GuardedBy; import org.apache.http.annotation.ThreadSafe; import org.apache.http.util.Args; /** * Maintains a map of objects keyed by a request URI pattern. *
* Patterns may have three formats: *

    *
  • *
  • *
  • *<uri>
  • *
  • <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 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 true if the request URI matches the pattern, * 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/ChainBuilder.java0100644 0000000 0000000 00000006571 12276755426 030623 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/HTTP.java0100644 0000000 0000000 00000010360 12276755426 027040 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.nio.charset.Charset; import org.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() { } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/protocol/RequestUserAgent.java0100644 0000000 0000000 00000005164 12276755426 031535 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.annotation.Immutable; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * RequestUserAgent is responsible for adding 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); } 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); } } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/0040755 0000000 0000000 00000000000 12276755424 024533 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/EncodingUtils.java0100644 0000000 0000000 00000012133 12276755424 030142 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import java.io.UnsupportedEncodingException; import org.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"); try { return data.getBytes(Consts.ASCII.name()); } catch (final UnsupportedEncodingException e) { throw new Error("ASCII not supported"); } } /** * 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"); try { return new String(data, offset, length, Consts.ASCII.name()); } catch (final UnsupportedEncodingException e) { throw new Error("ASCII not supported"); } } /** * 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() { } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/VersionInfo.java0100644 0000000 0000000 00000026750 12276755424 027646 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 null * @param release the release, or null * @param time the build time, or null * @param clsldr the class loader, or 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 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 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 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 null */ public final String getTimestamp() { return infoTimestamp; } /** * Obtains the classloader used to read the version information. * This is just the 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 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 * null for the thread context classloader * * @return the version information for all packages found, * never 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 "org.apache.http". * The package name should NOT end with a dot. * @param clsldr the classloader to load from, or * null for the thread context classloader * * @return the version information for the argument package, or * 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 { // org.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 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 1.5 minimum; Java/)"}. *

* For example: *

"Apache-HttpClient/4.3 (Java 1.5 minimum; 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 "org.apache.http". The package name * should NOT end with a dot. * @param cls * the class' class loader to load from, or 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 name + "/" + release + " (Java 1.5 minimum; Java/" + javaVersion + ")"; } } // class VersionInfo httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/Asserts.java0100644 0000000 0000000 00000004241 12276755424 027020 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 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"); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/EntityUtils.java0100644 0000000 0000000 00000025544 12276755424 027702 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.entity.ContentType; import org.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 * @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 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) { 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); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/CharsetUtils.java0100644 0000000 0000000 00000003705 12276755424 030012 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/NetUtils.java0100644 0000000 0000000 00000003741 12276755424 027147 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/Args.java0100644 0000000 0000000 00000007364 12276755424 026301 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 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 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; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/package-info.java0100644 0000000 0000000 00000002340 12276755424 027716 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.util; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/CharArrayBuffer.java0100644 0000000 0000000 00000040450 12276755424 030404 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import java.io.Serializable; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.protocol.HTTP; /** * A resizable char array. * * @since 4.0 */ @NotThreadSafe public final class CharArrayBuffer implements 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 len chars to this buffer from the given source * array starting at index off. The capacity of the buffer * is increased, if necessary, to accommodate all 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 off is out of * range, len is negative, or * off + 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 len chars to this buffer from the given source * buffer starting at index off. The capacity of the * destination buffer is increased, if necessary, to accommodate all * 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 off is out of * range, len is negative, or * off + 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 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 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 len bytes to this buffer from the given source * array starting at index off. The capacity of the buffer * is increased, if necessary, to accommodate all 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 off is out of * range, len is negative, or * off + 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 len bytes to this buffer from the given source * array starting at index off. The capacity of the buffer * is increased, if necessary, to accommodate all 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 off is out of * range, len is negative, or * off + 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 char value in this buffer at the specified * index. The index argument must be greater than or equal to * 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 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 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 * 0. * * @param len the new length * @throws IndexOutOfBoundsException if the * len argument is greater than the current * capacity of the buffer or less than 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 true if this buffer is empty, that is, its * {@link #length()} is equal to 0. * @return true if this buffer is empty, false * otherwise. */ public boolean isEmpty() { return this.len == 0; } /** * Returns true if this buffer is full, that is, its * {@link #length()} is equal to its {@link #capacity()}. * @return true if this buffer is full, 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 * beginIndex and finishing at endIndex. * If no such character occurs in this buffer within the specified bounds, * -1 is returned. *

* There is no restriction on the value of beginIndex and * endIndex. If beginIndex is negative, * it has the same effect as if it were zero. If endIndex is * greater than {@link #length()}, it has the same effect as if it were * {@link #length()}. If the beginIndex is greater than * the endIndex, -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 -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 0 and finishing * at {@link #length()}. If no such character occurs in this buffer within * those bounds, -1 is returned. * * @param ch the char to search for. * @return the index of the first occurrence of the character in the * buffer, or -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 * beginIndex and extends to the character at index * endIndex - 1. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception StringIndexOutOfBoundsException if the * beginIndex is negative, or * endIndex is larger than the length of this * buffer, or beginIndex is larger than * endIndex. */ public String substring(final int beginIndex, final int 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 beginIndex and extends to the last * non-whitespace character with the index lesser than * endIndex. * * @param from the beginning index, inclusive. * @param to the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * beginIndex is negative, or * endIndex is larger than the length of this * buffer, or beginIndex is larger than * endIndex. */ public String substringTrimmed(final int from, final int to) { int beginIndex = from; int endIndex = to; 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); } while (beginIndex < endIndex && HTTP.isWhitespace(this.buffer[beginIndex])) { beginIndex++; } while (endIndex > beginIndex && HTTP.isWhitespace(this.buffer[endIndex - 1])) { endIndex--; } return new String(this.buffer, beginIndex, endIndex - beginIndex); } @Override public String toString() { return new String(this.buffer, 0, this.len); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/ByteArrayBuffer.java0100644 0000000 0000000 00000027273 12276755424 030442 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import java.io.Serializable; import org.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 len bytes to this buffer from the given source * array starting at index off. The capacity of the buffer * is increased, if necessary, to accommodate all 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 off if out of * range, len is negative, or * off + 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 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 len chars to this buffer from the given source * array starting at index off. The capacity of the buffer * is increased if necessary to accommodate all 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 off if out of * range, len is negative, or * off + 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 len chars to this buffer from the given source * char array buffer starting at index off. The capacity * of the buffer is increased if necessary to accommodate all * 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 off if out of * range, len is negative, or * off + 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 byte value in this buffer at the specified * index. The index argument must be greater than or equal to * 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 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 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 * 0. * * @param len the new length * @throws IndexOutOfBoundsException if the * len argument is greater than the current * capacity of the buffer or less than 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 true if this buffer is empty, that is, its * {@link #length()} is equal to 0. * @return true if this buffer is empty, false * otherwise. */ public boolean isEmpty() { return this.len == 0; } /** * Returns true if this buffer is full, that is, its * {@link #length()} is equal to its {@link #capacity()}. * @return true if this buffer is full, 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 * beginIndex and finishing at endIndex. * If no such byte occurs in this buffer within the specified bounds, * -1 is returned. *

* There is no restriction on the value of beginIndex and * endIndex. If beginIndex is negative, * it has the same effect as if it were zero. If endIndex is * greater than {@link #length()}, it has the same effect as if it were * {@link #length()}. If the beginIndex is greater than * the endIndex, -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 -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 0 and finishing * at {@link #length()}. If no such byte occurs in this buffer within * those bounds, -1 is returned. * * @param b the byte to search for. * @return the index of the first occurrence of the byte in the * buffer, or -1 if the byte does not occur. * * @since 4.1 */ public int indexOf(final byte b) { return indexOf(b, 0, this.len); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/TextUtils.java0100644 0000000 0000000 00000003304 12276755424 027340 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; /** * @since 4.3 */ public final class TextUtils { public static boolean isEmpty(final CharSequence s) { if (s == null) { return true; } return s.length() == 0; } 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; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/util/LangUtils.java0100644 0000000 0000000 00000006627 12276755424 027310 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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; } } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/0040755 0000000 0000000 00000000000 12276755423 024164 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/EofSensor.java0100644 0000000 0000000 00000002520 12276755423 026726 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.io; /** * EOF sensor. * * @since 4.0 * * @deprecated (4.3) no longer used. */ @Deprecated public interface EofSensor { boolean isEof(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/HttpMessageWriterFactory.java0100644 0000000 0000000 00000002664 12276755423 032005 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.io; import org.apache.http.HttpMessage; /** * Factory for {@link HttpMessageWriter} instances. * * @since 4.3 */ public interface HttpMessageWriterFactory { HttpMessageWriter create(SessionOutputBuffer buffer); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/HttpMessageParserFactory.java0100644 0000000 0000000 00000003005 12276755423 031753 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.io; import org.apache.http.HttpMessage; import org.apache.http.config.MessageConstraints; /** * Factory for {@link HttpMessageParser} instances. * * @since 4.3 */ public interface HttpMessageParserFactory { HttpMessageParser create(SessionInputBuffer buffer, MessageConstraints constraints); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/BufferInfo.java0100644 0000000 0000000 00000003171 12276755423 027053 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/SessionInputBuffer.java0100644 0000000 0000000 00000014554 12276755423 030632 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.io; import java.io.IOException; import org.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 len bytes of data from the session buffer into * an array of bytes. An attempt is made to read as many as * 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 off is negative, or len is negative, or * off+len is greater than the length of the array * b, then an IndexOutOfBoundsException is * thrown. * * @param b the buffer into which the data is read. * @param off the start offset in array 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 * -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 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 * -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 int in the range 0 to * 255. If no byte is available because the end of the stream * has been reached, the value -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 -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 -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, * 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 * 0 this method blocks indefinitely. * * @param timeout in milliseconds. * @return true if some data is available in the session * buffer or 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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/HttpMessageWriter.java0100644 0000000 0000000 00000003447 12276755423 030455 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.io; import java.io.IOException; import org.apache.http.HttpException; import org.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/package-info.java0100644 0000000 0000000 00000002430 12276755423 027347 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.io; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/HttpMessageParser.java0100644 0000000 0000000 00000003525 12276755423 030432 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.io; import java.io.IOException; import org.apache.http.HttpException; import org.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/SessionOutputBuffer.java0100644 0000000 0000000 00000010336 12276755423 031025 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.io; import java.io.IOException; import org.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 len bytes from the specified byte array * starting at offset off to this session buffer. *

* If off is negative, or len is negative, or * off+len is greater than the length of the array * b, then an 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 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 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 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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/io/HttpTransportMetrics.java0100644 0000000 0000000 00000003011 12276755423 031202 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/annotation/0040755 0000000 0000000 00000000000 12276755424 025730 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/annotation/NotThreadSafe.java0100644 0000000 0000000 00000004100 12276755424 031252 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 { } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/annotation/ThreadSafe.java0100644 0000000 0000000 00000004217 12276755424 030602 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 { } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/annotation/package-info.java0100644 0000000 0000000 00000002533 12276755424 031117 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.annotation; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/annotation/Immutable.java0100644 0000000 0000000 00000005057 12276755424 030516 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 { } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/annotation/GuardedBy.java0100644 0000000 0000000 00000006042 12276755424 030440 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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: *

    *
  • * this : The intrinsic lock of the object in whose class the field is defined. *
  • *
  • * 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 *
  • *
  • * itself : For reference fields only; the object to which the field refers. *
  • *
  • * field-name : The lock object is referenced by the (instance or static) field * specified by field-name. *
  • *
  • * class-name.field-name : The lock object is reference by the static field specified * by class-name.field-name. *
  • *
  • * method-name() : The lock object is returned by calling the named nil-ary method. *
  • *
  • * 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(); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/0040755 0000000 0000000 00000000000 12276755423 024526 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/ConnFactory.java0100644 0000000 0000000 00000002772 12276755423 027623 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/RouteSpecificPool.java0100644 0000000 0000000 00000012504 12276755423 030766 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.pool; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Set; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; import org.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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/PoolEntry.java0100644 0000000 0000000 00000012721 12276755423 027324 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.pool; import java.util.concurrent.TimeUnit; import org.apache.http.annotation.GuardedBy; import org.apache.http.annotation.ThreadSafe; import org.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 validUnit; @GuardedBy("this") private long updated; @GuardedBy("this") private long expiry; private volatile Object state; /** * Creates new PoolEntry instance. * * @param id unique identifier of the pool entry. May be 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.validUnit = this.created + tunit.toMillis(timeToLive); } else { this.validUnit = Long.MAX_VALUE; } this.expiry = this.validUnit; } /** * Creates new PoolEntry instance without an expiry deadline. * * @param id unique identifier of the pool entry. May be 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; } public long getValidUnit() { return this.validUnit; } 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.validUnit); } 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 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/PoolEntryFuture.java0100644 0000000 0000000 00000011427 12276755423 030521 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.annotation.ThreadSafe; import org.apache.http.concurrent.FutureCallback; import org.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; } 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(); } } public boolean isCancelled() { return this.cancelled; } public boolean isDone() { return this.completed; } public T get() throws InterruptedException, ExecutionException { try { return get(0, TimeUnit.MILLISECONDS); } catch (final TimeoutException ex) { throw new ExecutionException(ex); } } 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(); } } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/ConnPool.java0100644 0000000 0000000 00000005023 12276755423 027115 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.pool; import java.util.concurrent.Future; import org.apache.http.concurrent.FutureCallback; /** * 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 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); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/AbstractConnPool.java0100644 0000000 0000000 00000043217 12276755423 030610 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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 org.apache.http.annotation.ThreadSafe; import org.apache.http.concurrent.FutureCallback; import org.apache.http.util.Args; import org.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; public AbstractConnPool( final ConnFactory connFactory, final int defaultMaxPerRoute, final int maxTotal) { super(); this.connFactory = Args.notNull(connFactory, "Connection factory"); this.defaultMaxPerRoute = Args.notNegative(defaultMaxPerRoute, "Max per route value"); this.maxTotal = Args.notNegative(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) { } 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. */ 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 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.isClosed() || entry.isExpired(System.currentTimeMillis())) { entry.close(); this.available.remove(entry); pool.free(entry, false); } else { break; } } if (entry != null) { this.available.remove(entry); this.leased.add(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(); } } 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; } } public void setMaxTotal(final int max) { Args.notNegative(max, "Max value"); this.lock.lock(); try { this.maxTotal = max; } finally { this.lock.unlock(); } } public int getMaxTotal() { this.lock.lock(); try { return this.maxTotal; } finally { this.lock.unlock(); } } public void setDefaultMaxPerRoute(final int max) { Args.notNegative(max, "Max per route value"); this.lock.lock(); try { this.defaultMaxPerRoute = max; } finally { this.lock.unlock(); } } public int getDefaultMaxPerRoute() { this.lock.lock(); try { return this.defaultMaxPerRoute; } finally { this.lock.unlock(); } } public void setMaxPerRoute(final T route, final int max) { Args.notNull(route, "Route"); Args.notNegative(max, "Max per route value"); this.lock.lock(); try { this.maxPerRoute.put(route, Integer.valueOf(max)); } finally { this.lock.unlock(); } } public int getMaxPerRoute(final T route) { Args.notNull(route, "Route"); this.lock.lock(); try { return getMax(route); } finally { this.lock.unlock(); } } 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(); } } 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(); } } /** * 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() { 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() { public void process(final PoolEntry entry) { if (entry.isExpired(now)) { entry.close(); } } }); } @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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/ConnPoolControl.java0100644 0000000 0000000 00000003444 12276755423 030463 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/PoolEntryCallback.java0100644 0000000 0000000 00000002713 12276755423 030741 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.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); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/package-info.java0100644 0000000 0000000 00000002430 12276755423 027711 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.pool; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/pool/PoolStats.java0100644 0000000 0000000 00000006766 12276755423 027335 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.pool; import org.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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/0040755 0000000 0000000 00000000000 12276755425 025203 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/LineParser.java0100644 0000000 0000000 00000012363 12276755425 030114 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.Header; import org.apache.http.ParseException; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.StatusLine; import org.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 true if there is a protocol version at the * argument index (possibly ignoring whitespace), * 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; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicLineParser.java0100644 0000000 0000000 00000037013 12276755425 031055 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.Header; import org.apache.http.HttpVersion; import org.apache.http.ParseException; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.StatusLine; import org.apache.http.annotation.Immutable; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; import org.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 * 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 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 org.apache.http.message; import java.util.NoSuchElementException; import org.apache.http.FormattedHeader; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HeaderElementIterator; import org.apache.http.HeaderIterator; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; import org.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; } } } } public boolean hasNext() { if (this.currentElement == null) { parseNextElement(); } return this.currentElement != null; } 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; } public final Object next() throws NoSuchElementException { return nextElement(); } public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("Remove not supported"); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/HeaderValueFormatter.java0100644 0000000 0000000 00000012131 12276755425 032112 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.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 * null to create a new buffer * @param elems the header elements to format * @param quote true to always format with quoted values, * false to use quotes only when necessary * * @return a buffer with the formatted header elements. * If the buffer argument was not 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 * null to create a new buffer * @param elem the header element to format * @param quote true to always format with quoted values, * false to use quotes only when necessary * * @return a buffer with the formatted header element. * If the buffer argument was not 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 * null to create a new buffer * @param nvps the parameters (name-value pairs) to format * @param quote true to always format with quoted values, * false to use quotes only when necessary * * @return a buffer with the formatted parameters. * If the buffer argument was not 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 * null to create a new buffer * @param nvp the name-value pair to format * @param quote true to always format with a quoted value, * false to use quotes only when necessary * * @return a buffer with the formatted name-value pair. * If the buffer argument was not null, * that buffer will be used and returned. */ CharArrayBuffer formatNameValuePair(CharArrayBuffer buffer, NameValuePair nvp, boolean quote); } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicNameValuePair.java0100644 0000000 0000000 00000006433 12276755425 031504 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.Serializable; import org.apache.http.NameValuePair; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; import org.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; } public String getName() { return this.name; } 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/LineFormatter.java0100644 0000000 0000000 00000012327 12276755425 030623 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.Header; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.StatusLine; import org.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 * 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 * 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 * formatProtocolVersion. * * @param buffer a buffer to which to append, or 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 buffer argument is not 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 * 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 * null. * The buffer will be cleared before use. * @param statline the status line to format * * @return the formatted status line * * @throws org.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 * null. * The buffer will be cleared before use. * @param header the header to format * * @return a buffer holding the formatted header, never null. * The returned buffer may be different from the argument buffer. * * @throws org.apache.http.ParseException in case of a parse error */ CharArrayBuffer formatHeader(CharArrayBuffer buffer, Header header); } ././@LongLink0100644 0000000 0000000 00000000146 12276757360 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicListHeaderIterator.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicListHeaderIterator.jav0100644 0000000 0000000 00000012677 12276755425 032417 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.util.List; import java.util.NoSuchElementException; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; import org.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. * 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 * 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 true if the header should be part of the * iteration, 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 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 */ 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 */ public final Object next() throws NoSuchElementException { return nextHeader(); } /** * Removes the header that was returned last. */ 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 } } ././@LongLink0100644 0000000 0000000 00000000156 12276757360 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHttpEntityEnclosingRequest.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHttpEntityEnclosingReq0100644 0000000 0000000 00000004727 12276755425 032525 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.annotation.NotThreadSafe; import org.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); } public HttpEntity getEntity() { return this.entity; } public void setEntity(final HttpEntity entity) { this.entity = entity; } public boolean expectContinue() { final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHeaderIterator.java0100644 0000000 0000000 00000012050 12276755425 031705 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.util.NoSuchElementException; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.annotation.NotThreadSafe; import org.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. * 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 * 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 true if the header should be part of the * iteration, 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 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 */ 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 */ public final Object next() throws NoSuchElementException { return nextHeader(); } /** * Removing headers is not supported. * * @throws UnsupportedOperationException always */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException ("Removing headers is not supported."); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicRequestLine.java0100644 0000000 0000000 00000005102 12276755425 031243 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.Serializable; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.annotation.Immutable; import org.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"); } public String getMethod() { return this.method; } public ProtocolVersion getProtocolVersion() { return this.protoversion; } 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/HeaderValueParser.java0100644 0000000 0000000 00000012060 12276755425 031404 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.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 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 parse 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 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 null * if no value is specified */ NameValuePair parseNameValuePair( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHeader.java0100644 0000000 0000000 00000005341 12276755425 030200 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.Serializable; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.ParseException; import org.apache.http.annotation.Immutable; import org.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; } public String getName() { return this.name; } 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(); } 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/package-info.java0100644 0000000 0000000 00000002470 12276755425 030372 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 org.apache.http.message; httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHttpRequest.java0100644 0000000 0000000 00000007075 12276755425 031306 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HttpRequest; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.annotation.NotThreadSafe; import org.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) */ public ProtocolVersion getProtocolVersion() { return getRequestLine().getProtocolVersion(); } /** * Returns the request line of this request. * * @see #BasicHttpRequest(String, String) */ 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; } } ././@LongLink0100644 0000000 0000000 00000000145 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHeaderValueParser.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHeaderValueParser.java0100644 0000000 0000000 00000030227 12276755425 032353 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.util.ArrayList; import java.util.List; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.annotation.Immutable; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; import org.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 = ','; private final static char[] ALL_DELIMITERS = new char[] { PARAM_DELIMITER, ELEM_DELIMITER }; public BasicHeaderValueParser() { super(); } /** * Parses elements with the given parser. * * @param value the header value to parse * @param parser the parser to use, or null for default * * @return array holding the header elements, never null */ 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 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 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 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 null for default * * @return array holding the parameters, never 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 public NameValuePair[] parseParameters(final CharArrayBuffer buffer, final ParserCursor cursor) { Args.notNull(buffer, "Char array buffer"); Args.notNull(cursor, "Parser cursor"); int pos = cursor.getPos(); final int indexTo = cursor.getUpperBound(); while (pos < indexTo) { final char ch = buffer.charAt(pos); if (HTTP.isWhitespace(ch)) { pos++; } else { break; } } cursor.updatePos(pos); if (cursor.atEnd()) { return new NameValuePair[] {}; } 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 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 public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor) { return parseNameValuePair(buffer, cursor, ALL_DELIMITERS); } private static boolean isOneOf(final char ch, final char[] chs) { if (chs != null) { for (final char ch2 : chs) { if (ch == ch2) { return true; } } } return false; } public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor, final char[] delimiters) { Args.notNull(buffer, "Char array buffer"); Args.notNull(cursor, "Parser cursor"); boolean terminated = false; int pos = cursor.getPos(); final int indexFrom = cursor.getPos(); final int indexTo = cursor.getUpperBound(); // Find name final String name; while (pos < indexTo) { final char ch = buffer.charAt(pos); if (ch == '=') { break; } if (isOneOf(ch, delimiters)) { terminated = true; break; } pos++; } if (pos == indexTo) { terminated = true; name = buffer.substringTrimmed(indexFrom, indexTo); } else { name = buffer.substringTrimmed(indexFrom, pos); pos++; } if (terminated) { cursor.updatePos(pos); return createNameValuePair(name, null); } // Find value final String value; int i1 = pos; boolean qouted = false; boolean escaped = false; while (pos < indexTo) { final char ch = buffer.charAt(pos); if (ch == '"' && !escaped) { qouted = !qouted; } if (!qouted && !escaped && isOneOf(ch, delimiters)) { terminated = true; break; } if (escaped) { escaped = false; } else { escaped = qouted && ch == '\\'; } pos++; } int i2 = pos; // Trim leading white spaces while (i1 < i2 && (HTTP.isWhitespace(buffer.charAt(i1)))) { i1++; } // Trim trailing white spaces while ((i2 > i1) && (HTTP.isWhitespace(buffer.charAt(i2 - 1)))) { i2--; } // Strip away quotes if necessary if (((i2 - i1) >= 2) && (buffer.charAt(i1) == '"') && (buffer.charAt(i2 - 1) == '"')) { i1++; i2--; } value = buffer.substring(i1, i2); if (terminated) { pos++; } cursor.updatePos(pos); return createNameValuePair(name, value); } /** * Creates a name-value pair. * Called from {@link #parseNameValuePair}. * * @param name the name * @param value the value, or null * * @return a name-value pair representing the arguments */ protected NameValuePair createNameValuePair(final String name, final String value) { return new BasicNameValuePair(name, value); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHttpResponse.java0100644 0000000 0000000 00000016524 12276755425 031453 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.util.Locale; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.apache.http.ReasonPhraseCatalog; import org.apache.http.StatusLine; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; /** * Basic implementation of {@link HttpResponse}. * * @see org.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 * null to disable automatic * reason phrase lookup * @param locale the locale for looking up reason phrases, or * 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 * 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 public ProtocolVersion getProtocolVersion() { return this.ver; } // non-javadoc, see interface HttpResponse 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 public HttpEntity getEntity() { return this.entity; } public Locale getLocale() { return this.locale; } // non-javadoc, see interface HttpResponse 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 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 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 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 public void setReasonPhrase(final String reason) { this.statusline = null; this.reasonPhrase = reason; } // non-javadoc, see interface HttpResponse public void setEntity(final HttpEntity entity) { this.entity = entity; } 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 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() { return getStatusLine() + " " + this.headergroup; } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHeaderElement.java0100644 0000000 0000000 00000011563 12276755425 031515 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; import org.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 null * @param parameters header element parameters. May be 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 null */ public BasicHeaderElement(final String name, final String value) { this(name, value, null); } public String getName() { return this.name; } public String getValue() { return this.value; } public NameValuePair[] getParameters() { return this.parameters.clone(); } public int getParameterCount() { return this.parameters.length; } public NameValuePair getParameter(final int index) { // ArrayIndexOutOfBoundsException is appropriate return this.parameters[index]; } 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicStatusLine.java0100644 0000000 0000000 00000006413 12276755425 031104 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.Serializable; import org.apache.http.ProtocolVersion; import org.apache.http.StatusLine; import org.apache.http.annotation.Immutable; import org.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 * 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 public int getStatusCode() { return this.statusCode; } public ProtocolVersion getProtocolVersion() { return this.protoVersion; } 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/ParserCursor.java0100644 0000000 0000000 00000006167 12276755425 030507 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicTokenIterator.java0100644 0000000 0000000 00000034253 12276755425 031606 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.util.NoSuchElementException; import org.apache.http.HeaderIterator; import org.apache.http.ParseException; import org.apache.http.TokenIterator; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; /** * Basic implementation of a {@link TokenIterator}. * This implementation parses #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()}. * 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 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 */ 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 */ public final Object next() throws NoSuchElementException, ParseException { return nextToken(); } /** * Removing tokens is not supported. * * @throws UnsupportedOperationException always */ 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 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 #. */ 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 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 * #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 true if the character is a token separator, * 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 true if the character is whitespace, * 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 true if the character is a valid token start, * 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 true if the character is an HTTP separator */ protected boolean isHttpSeparator(final char ch) { return (HTTP_SEPARATORS.indexOf(ch) >= 0); } } // class BasicTokenIterator httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/HeaderGroup.java0100644 0000000 0000000 00000023051 12276755425 030251 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.annotation.NotThreadSafe; import org.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 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.ENGLISH), 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 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 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 true if at least one header with the name is * contained, 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 * 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BufferedHeader.java0100644 0000000 0000000 00000007524 12276755425 030706 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.Serializable; import org.apache.http.FormattedHeader; import org.apache.http.HeaderElement; import org.apache.http.ParseException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; import org.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; } public String getName() { return this.name; } public String getValue() { return this.buffer.substringTrimmed(this.valuePos, this.buffer.length()); } 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); } public int getValuePos() { return this.valuePos; } 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(); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/AbstractHttpMessage.java0100644 0000000 0000000 00000012130 12276755425 031750 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpMessage; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.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 public boolean containsHeader(final String name) { return this.headergroup.containsHeader(name); } // non-javadoc, see interface HttpMessage public Header[] getHeaders(final String name) { return this.headergroup.getHeaders(name); } // non-javadoc, see interface HttpMessage public Header getFirstHeader(final String name) { return this.headergroup.getFirstHeader(name); } // non-javadoc, see interface HttpMessage public Header getLastHeader(final String name) { return this.headergroup.getLastHeader(name); } // non-javadoc, see interface HttpMessage public Header[] getAllHeaders() { return this.headergroup.getAllHeaders(); } // non-javadoc, see interface HttpMessage public void addHeader(final Header header) { this.headergroup.addHeader(header); } // non-javadoc, see interface HttpMessage 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 public void setHeader(final Header header) { this.headergroup.updateHeader(header); } // non-javadoc, see interface HttpMessage 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 public void setHeaders(final Header[] headers) { this.headergroup.setHeaders(headers); } // non-javadoc, see interface HttpMessage public void removeHeader(final Header header) { this.headergroup.removeHeader(header); } // non-javadoc, see interface HttpMessage 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 public HeaderIterator headerIterator() { return this.headergroup.iterator(); } // non-javadoc, see interface HttpMessage public HeaderIterator headerIterator(final String name) { return this.headergroup.iterator(name); } /** * @deprecated (4.3) use constructor parameters of configuration API provided by HttpClient */ @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 */ @Deprecated public void setParams(final HttpParams params) { this.params = Args.notNull(params, "HTTP parameters"); } } httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicLineFormatter.java0100644 0000000 0000000 00000025777 12276755425 031602 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.FormattedHeader; import org.apache.http.Header; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.StatusLine; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; import org.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 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 * 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 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 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 * 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 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 null * @param reqline the request line to format, never 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 * 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 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 null * @param statline the status line to format, never 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 * 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 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 null * @param header the header to format, never 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 ././@LongLink0100644 0000000 0000000 00000000150 12276757361 011647 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHeaderValueFormatter.javahttpcomponents-core-4.3.2/httpcore/src/main/java/org/apache/http/message/BasicHeaderValueFormatter.j0100644 0000000 0000000 00000033643 12276755425 032377 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; import org.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 true to always format with quoted values, * false to use quotes only when necessary * @param formatter the formatter to use, or 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 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 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 true to always format with quoted values, * false to use quotes only when necessary * @param formatter the formatter to use, or 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 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; inull * * @return a length estimate, in number of characters */ protected int estimateHeaderElementLen(final HeaderElement elem) { if (elem == null) { return 0; } int result = elem.getName().length(); // name final String value = elem.getValue(); if (value != null) { // assume quotes, but no escaped characters result += 3 + value.length(); // ="value" } final int parcnt = elem.getParameterCount(); if (parcnt > 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 true to always format with quoted values, * false to use quotes only when necessary * @param formatter the formatter to use, or 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 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 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 true to always format with a quoted value, * false to use quotes only when necessary * @param formatter the formatter to use, or 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 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 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 null * @param value the value to append, never null * @param quote true to always format with quotes, * 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 true if the character is a separator, * 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 true if the character is unsafe, * false otherwise */ protected boolean isUnsafe(final char ch) { return UNSAFE_CHARS.indexOf(ch) >= 0; } } // class BasicHeaderValueFormatter httpcomponents-core-4.3.2/httpcore/src/main/appended-resources/0040755 0000000 0000000 00000000000 12276755422 023434 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/appended-resources/META-INF/0040755 0000000 0000000 00000000000 12276755422 024574 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/main/appended-resources/META-INF/NOTICE0100644 0000000 0000000 00000000210 12276755422 025466 0ustar000000000 0000000 This project contains annotations derived from JCIP-ANNOTATIONS Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net httpcomponents-core-4.3.2/httpcore/src/main/appended-resources/META-INF/LICENSE0100644 0000000 0000000 00000026564 12276755422 025613 0ustar000000000 0000000 ========================================================================= This project contains annotations in the package org.apache.http.annotation which are derived from JCIP-ANNOTATIONS Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net and the Creative Commons Attribution License (http://creativecommons.org/licenses/by/2.5) Full text: http://creativecommons.org/licenses/by/2.5/legalcode License THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 1. Definitions "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License. "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License. "Licensor" means the individual or entity that offers the Work under the terms of this License. "Original Author" means the individual or entity who created the Work. "Work" means the copyrightable work of authorship offered under the terms of this License. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. 2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws. 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; to create and reproduce Derivative Works; to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works; to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works. For the avoidance of doubt, where the work is a musical composition: Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work. Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions). Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions). The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved. 4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(b), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(b), as requested. If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit. 5. Representations, Warranties and Disclaimer UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. Termination This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 8. Miscellaneous Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. httpcomponents-core-4.3.2/httpcore/src/test/0040755 0000000 0000000 00000000000 12276755417 017703 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/0040755 0000000 0000000 00000000000 12276755417 020624 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/0040755 0000000 0000000 00000000000 12276755417 021413 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/0040755 0000000 0000000 00000000000 12276755417 022634 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/0040755 0000000 0000000 00000000000 12276755422 023607 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/TestHttpExceptions.java0100644 0000000 0000000 00000003673 12276755420 030277 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import org.junit.Test; /** * Simple tests for various HTTP exception classes. * * */ public class TestHttpExceptions { @Test public void testConstructor() { final Throwable cause = new Exception(); new HttpException(); new HttpException("Oppsie"); new HttpException("Oppsie", cause); new ProtocolException(); new ProtocolException("Oppsie"); new ProtocolException("Oppsie", cause); new NoHttpResponseException("Oppsie"); new ConnectionClosedException("Oppsie"); new MethodNotSupportedException("Oppsie"); new MethodNotSupportedException("Oppsie", cause); new UnsupportedHttpVersionException(); new UnsupportedHttpVersionException("Oppsie"); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/TestHttpHost.java0100644 0000000 0000000 00000017372 12276755420 027074 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link HttpHost}. * */ public class TestHttpHost { @Test public void testConstructor() { final HttpHost host1 = new HttpHost("somehost"); Assert.assertEquals("somehost", host1.getHostName()); Assert.assertEquals(-1, host1.getPort()); Assert.assertEquals("http", host1.getSchemeName()); final HttpHost host2 = new HttpHost("somehost", 8080); Assert.assertEquals("somehost", host2.getHostName()); Assert.assertEquals(8080, host2.getPort()); Assert.assertEquals("http", host2.getSchemeName()); final HttpHost host3 = new HttpHost("somehost", -1); Assert.assertEquals("somehost", host3.getHostName()); Assert.assertEquals(-1, host3.getPort()); Assert.assertEquals("http", host3.getSchemeName()); final HttpHost host4 = new HttpHost("somehost", 443, "https"); Assert.assertEquals("somehost", host4.getHostName()); Assert.assertEquals(443, host4.getPort()); Assert.assertEquals("https", host4.getSchemeName()); try { new HttpHost((String) null, -1, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { new HttpHost(" ", -1, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { new HttpHost((InetAddress) null, -1, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } } @Test public void testHashCode() throws Exception { final HttpHost host1 = new HttpHost("somehost", 8080, "http"); final HttpHost host2 = new HttpHost("somehost", 80, "http"); final HttpHost host3 = new HttpHost("someotherhost", 8080, "http"); final HttpHost host4 = new HttpHost("somehost", 80, "http"); final HttpHost host5 = new HttpHost("SomeHost", 80, "http"); final HttpHost host6 = new HttpHost("SomeHost", 80, "myhttp"); final HttpHost host7 = new HttpHost( InetAddress.getByAddress(new byte[] {127,0,0,1}), 80, "http"); final HttpHost host8 = new HttpHost("127.0.0.1", 80, "http"); Assert.assertTrue(host1.hashCode() == host1.hashCode()); Assert.assertTrue(host1.hashCode() != host2.hashCode()); Assert.assertTrue(host1.hashCode() != host3.hashCode()); Assert.assertTrue(host2.hashCode() == host4.hashCode()); Assert.assertTrue(host2.hashCode() == host5.hashCode()); Assert.assertTrue(host5.hashCode() != host6.hashCode()); Assert.assertTrue(host7.hashCode() == host8.hashCode()); } @Test public void testEquals() throws Exception { final HttpHost host1 = new HttpHost("somehost", 8080, "http"); final HttpHost host2 = new HttpHost("somehost", 80, "http"); final HttpHost host3 = new HttpHost("someotherhost", 8080, "http"); final HttpHost host4 = new HttpHost("somehost", 80, "http"); final HttpHost host5 = new HttpHost("SomeHost", 80, "http"); final HttpHost host6 = new HttpHost("SomeHost", 80, "myhttp"); final HttpHost host7 = new HttpHost( InetAddress.getByAddress(new byte[] {127,0,0,1}), 80, "http"); final HttpHost host8 = new HttpHost("127.0.0.1", 80, "http"); Assert.assertTrue(host1.equals(host1)); Assert.assertFalse(host1.equals(host2)); Assert.assertFalse(host1.equals(host3)); Assert.assertTrue(host2.equals(host4)); Assert.assertTrue(host2.equals(host5)); Assert.assertFalse(host5.equals(host6)); Assert.assertTrue(host7.equals(host8)); Assert.assertFalse(host1.equals(null)); Assert.assertFalse(host1.equals("http://somehost")); } @Test public void testToString() throws Exception { final HttpHost host1 = new HttpHost("somehost"); Assert.assertEquals("http://somehost", host1.toString()); final HttpHost host2 = new HttpHost("somehost", -1); Assert.assertEquals("http://somehost", host2.toString()); final HttpHost host3 = new HttpHost("somehost", -1); Assert.assertEquals("http://somehost", host3.toString()); final HttpHost host4 = new HttpHost("somehost", 8888); Assert.assertEquals("http://somehost:8888", host4.toString()); final HttpHost host5 = new HttpHost("somehost", -1, "myhttp"); Assert.assertEquals("myhttp://somehost", host5.toString()); final HttpHost host6 = new HttpHost("somehost", 80, "myhttp"); Assert.assertEquals("myhttp://somehost:80", host6.toString()); final HttpHost host7 = new HttpHost( InetAddress.getByAddress(new byte[] {127,0,0,1}), 80, "http"); Assert.assertEquals("http://127.0.0.1:80", host7.toString()); } @Test public void testToHostString() { final HttpHost host1 = new HttpHost("somehost"); Assert.assertEquals("somehost", host1.toHostString()); final HttpHost host2 = new HttpHost("somehost"); Assert.assertEquals("somehost", host2.toHostString()); final HttpHost host3 = new HttpHost("somehost", -1); Assert.assertEquals("somehost", host3.toHostString()); final HttpHost host4 = new HttpHost("somehost", 8888); Assert.assertEquals("somehost:8888", host4.toHostString()); } @Test public void testCloning() throws Exception { final HttpHost orig = new HttpHost("somehost", 8080, "https"); final HttpHost clone = (HttpHost) orig.clone(); Assert.assertEquals(orig, clone); } @Test public void testSerialization() throws Exception { final HttpHost orig = new HttpHost("somehost", 8080, "https"); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final HttpHost clone = (HttpHost) instream.readObject(); Assert.assertEquals(orig, clone); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/TestHttpVersion.java0100644 0000000 0000000 00000012050 12276755422 027572 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.junit.Assert; import org.junit.Test; /** * Test cases for HTTP version class * */ public class TestHttpVersion { @Test public void testHttpVersionInvalidConstructorInput() throws Exception { try { new HttpVersion(-1, -1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { // expected } try { new HttpVersion(0, -1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { // expected } } @Test public void testHttpVersionEquality() throws Exception { final HttpVersion ver1 = new HttpVersion(1, 1); final HttpVersion ver2 = new HttpVersion(1, 1); Assert.assertEquals(ver1.hashCode(), ver2.hashCode()); Assert.assertTrue(ver1.equals(ver1)); Assert.assertTrue(ver1.equals(ver2)); Assert.assertTrue(ver1.equals(ver1)); Assert.assertTrue(ver1.equals(ver2)); Assert.assertFalse(ver1.equals(new Float(1.1))); Assert.assertTrue((new HttpVersion(0, 9)).equals(HttpVersion.HTTP_0_9)); Assert.assertTrue((new HttpVersion(1, 0)).equals(HttpVersion.HTTP_1_0)); Assert.assertTrue((new HttpVersion(1, 1)).equals(HttpVersion.HTTP_1_1)); Assert.assertFalse((new HttpVersion(1, 1)).equals(HttpVersion.HTTP_1_0)); Assert.assertTrue ((new ProtocolVersion("HTTP", 0, 9)).equals(HttpVersion.HTTP_0_9)); Assert.assertTrue ((new ProtocolVersion("HTTP", 1, 0)).equals(HttpVersion.HTTP_1_0)); Assert.assertTrue ((new ProtocolVersion("HTTP", 1, 1)).equals(HttpVersion.HTTP_1_1)); Assert.assertFalse ((new ProtocolVersion("http", 1, 1)).equals(HttpVersion.HTTP_1_1)); Assert.assertTrue (HttpVersion.HTTP_0_9.equals(new ProtocolVersion("HTTP", 0, 9))); Assert.assertTrue (HttpVersion.HTTP_1_0.equals(new ProtocolVersion("HTTP", 1, 0))); Assert.assertTrue (HttpVersion.HTTP_1_1.equals(new ProtocolVersion("HTTP", 1, 1))); Assert.assertFalse (HttpVersion.HTTP_1_1.equals(new ProtocolVersion("http", 1, 1))); } @Test public void testHttpVersionComparison() { Assert.assertTrue(HttpVersion.HTTP_0_9.lessEquals(HttpVersion.HTTP_1_1)); Assert.assertTrue(HttpVersion.HTTP_0_9.greaterEquals(HttpVersion.HTTP_0_9)); Assert.assertFalse(HttpVersion.HTTP_0_9.greaterEquals(HttpVersion.HTTP_1_0)); Assert.assertTrue(HttpVersion.HTTP_1_0.compareToVersion(HttpVersion.HTTP_1_1) < 0); Assert.assertTrue(HttpVersion.HTTP_1_0.compareToVersion(HttpVersion.HTTP_0_9) > 0); Assert.assertTrue(HttpVersion.HTTP_1_0.compareToVersion(HttpVersion.HTTP_1_0) == 0); } @Test public void testCloning() throws Exception { final HttpVersion orig = HttpVersion.HTTP_1_1; final HttpVersion clone = (HttpVersion) orig.clone(); Assert.assertEquals(orig, clone); } @Test public void testSerialization() throws Exception { final HttpVersion orig = HttpVersion.HTTP_1_1; final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final HttpVersion clone = (HttpVersion) instream.readObject(); Assert.assertEquals(orig, clone); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/concurrent/0040755 0000000 0000000 00000000000 12276755421 025770 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/concurrent/TestBasicFuture.java0100644 0000000 0000000 00000017263 12276755421 031715 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.concurrent; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Assert; import org.junit.Test; public class TestBasicFuture { @Test public void testCompleted() throws Exception { final BasicFutureCallback callback = new BasicFutureCallback(); final BasicFuture future = new BasicFuture(callback); Assert.assertFalse(future.isDone()); final Object result = new Object(); final Exception boom = new Exception(); future.completed(result); future.failed(boom); Assert.assertTrue(callback.isCompleted()); Assert.assertSame(result, callback.getResult()); Assert.assertFalse(callback.isFailed()); Assert.assertNull(callback.getException()); Assert.assertFalse(callback.isCancelled()); Assert.assertSame(result, future.get()); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); } @Test public void testCompletedWithTimeout() throws Exception { final BasicFutureCallback callback = new BasicFutureCallback(); final BasicFuture future = new BasicFuture(callback); Assert.assertFalse(future.isDone()); final Object result = new Object(); final Exception boom = new Exception(); future.completed(result); future.failed(boom); Assert.assertTrue(callback.isCompleted()); Assert.assertSame(result, callback.getResult()); Assert.assertFalse(callback.isFailed()); Assert.assertNull(callback.getException()); Assert.assertFalse(callback.isCancelled()); Assert.assertSame(result, future.get(1, TimeUnit.MILLISECONDS)); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); } @Test public void testFailed() throws Exception { final BasicFutureCallback callback = new BasicFutureCallback(); final BasicFuture future = new BasicFuture(callback); final Object result = new Object(); final Exception boom = new Exception(); future.failed(boom); future.completed(result); Assert.assertFalse(callback.isCompleted()); Assert.assertNull(callback.getResult()); Assert.assertTrue(callback.isFailed()); Assert.assertSame(boom, callback.getException()); Assert.assertFalse(callback.isCancelled()); try { future.get(); } catch (final ExecutionException ex) { Assert.assertSame(boom, ex.getCause()); } Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); } @Test public void testCancelled() throws Exception { final BasicFutureCallback callback = new BasicFutureCallback(); final BasicFuture future = new BasicFuture(callback); final Object result = new Object(); final Exception boom = new Exception(); future.cancel(true); future.failed(boom); future.completed(result); Assert.assertFalse(callback.isCompleted()); Assert.assertNull(callback.getResult()); Assert.assertFalse(callback.isFailed()); Assert.assertNull(callback.getException()); Assert.assertTrue(callback.isCancelled()); Assert.assertNull(future.get()); Assert.assertTrue(future.isDone()); Assert.assertTrue(future.isCancelled()); } @Test public void testAsyncCompleted() throws Exception { final BasicFuture future = new BasicFuture(null); final Object result = new Object(); final Thread t = new Thread() { @Override public void run() { try { Thread.sleep(100); future.completed(result); } catch (final InterruptedException boom) { } } }; t.setDaemon(true); t.start(); Assert.assertSame(result, future.get(60, TimeUnit.SECONDS)); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); } @Test public void testAsyncFailed() throws Exception { final BasicFuture future = new BasicFuture(null); final Exception boom = new Exception(); final Thread t = new Thread() { @Override public void run() { try { Thread.sleep(100); future.failed(boom); } catch (final InterruptedException ex) { } } }; t.setDaemon(true); t.start(); try { future.get(60, TimeUnit.SECONDS); } catch (final ExecutionException ex) { Assert.assertSame(boom, ex.getCause()); } Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); } @Test public void testAsyncCancelled() throws Exception { final BasicFuture future = new BasicFuture(null); final Thread t = new Thread() { @Override public void run() { try { Thread.sleep(100); future.cancel(true); } catch (final InterruptedException ex) { } } }; t.setDaemon(true); t.start(); Assert.assertNull(future.get(60, TimeUnit.SECONDS)); Assert.assertTrue(future.isDone()); Assert.assertTrue(future.isCancelled()); } @Test(expected=TimeoutException.class) public void testAsyncTimeout() throws Exception { final BasicFuture future = new BasicFuture(null); final Object result = new Object(); final Thread t = new Thread() { @Override public void run() { try { Thread.sleep(200); future.completed(result); } catch (final InterruptedException ex) { } } }; t.setDaemon(true); t.start(); future.get(1, TimeUnit.MILLISECONDS); } @Test(expected=TimeoutException.class) public void testAsyncNegativeTimeout() throws Exception { final BasicFuture future = new BasicFuture(null); future.get(-1, TimeUnit.MILLISECONDS); } } ././@LongLink0100644 0000000 0000000 00000000145 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/concurrent/BasicFutureCallback.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/concurrent/BasicFutureCallback.java0100644 0000000 0000000 00000004002 12276755421 032455 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.concurrent; class BasicFutureCallback implements FutureCallback { private T result; private Exception ex; private boolean completed; private boolean failed; private boolean cancelled; public void completed(final T result) { this.result = result; this.completed = true; } public T getResult() { return this.result; } public Exception getException() { return this.ex; } public void failed(final Exception ex) { this.ex = ex; this.failed = true; } public void cancelled() { this.cancelled = true; } public boolean isCompleted() { return this.completed; } public boolean isFailed() { return this.failed; } public boolean isCancelled() { return this.cancelled; } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/integration/0040755 0000000 0000000 00000000000 12276755421 026131 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/integration/TestSyncHttp.java0100644 0000000 0000000 00000110547 12276755421 031415 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.integration; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.http.Header; import org.apache.http.HttpConnectionMetrics; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.DefaultBHttpClientConnection; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.testserver.HttpClient; import org.apache.http.testserver.HttpServer; import org.apache.http.util.EncodingUtils; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestSyncHttp { private HttpServer server; private HttpClient client; @Before public void initServer() throws Exception { this.server = new HttpServer(); this.server.setTimeout(5000); } @Before public void initClient() throws Exception { this.client = new HttpClient(); this.client.setTimeout(5000); } @After public void shutDownServer() throws Exception { if (this.server != null) { this.server.shutdown(); } } /** * This test case executes a series of simple GET requests */ @Test public void testSimpleBasicHttpRequests() throws Exception { final int reqNo = 20; final Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { final int size = rnd.nextInt(5000); final byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String s = request.getRequestLine().getUri(); if (s.startsWith("/?")) { s = s.substring(2); } final int index = Integer.parseInt(s); final byte[] data = testData.get(index); final ByteArrayEntity entity = new ByteArrayEntity(data); response.setEntity(entity); } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r); final HttpResponse response = this.client.execute(get, host, conn); final byte[] received = EntityUtils.toByteArray(response.getEntity()); final byte[] expected = testData.get(r); Assert.assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics final HttpConnectionMetrics cm = conn.getMetrics(); Assert.assertEquals(reqNo, cm.getRequestCount()); Assert.assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } /** * This test case executes a series of simple POST requests with content length * delimited content. */ @Test public void testSimpleHttpPostsWithContentLength() throws Exception { final int reqNo = 20; final Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { final int size = rnd.nextInt(5000); final byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final byte[] data = EntityUtils.toByteArray(incoming); final ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { final StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); final byte[] data = testData.get(r); final ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); final HttpResponse response = this.client.execute(post, host, conn); final byte[] received = EntityUtils.toByteArray(response.getEntity()); final byte[] expected = testData.get(r); Assert.assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics final HttpConnectionMetrics cm = conn.getMetrics(); Assert.assertEquals(reqNo, cm.getRequestCount()); Assert.assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } /** * This test case executes a series of simple POST requests with chunk * coded content content. */ @Test public void testSimpleHttpPostsChunked() throws Exception { final int reqNo = 20; final Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { final int size = rnd.nextInt(20000); final byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final byte[] data = EntityUtils.toByteArray(incoming); final ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { final StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); final byte[] data = testData.get(r); final ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); final HttpResponse response = this.client.execute(post, host, conn); final byte[] received = EntityUtils.toByteArray(response.getEntity()); final byte[] expected = testData.get(r); Assert.assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics final HttpConnectionMetrics cm = conn.getMetrics(); Assert.assertEquals(reqNo, cm.getRequestCount()); Assert.assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } /** * This test case executes a series of simple HTTP/1.0 POST requests. */ @Test public void testSimpleHttpPostsHTTP10() throws Exception { final int reqNo = 20; final Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { final int size = rnd.nextInt(5000); final byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final byte[] data = EntityUtils.toByteArray(incoming); final ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { final StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { client.connect(host, conn); } // Set protocol level to HTTP/1.0 final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest( "POST", "/", HttpVersion.HTTP_1_0); final byte[] data = testData.get(r); final ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); final HttpResponse response = this.client.execute(post, host, conn); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); final byte[] received = EntityUtils.toByteArray(response.getEntity()); final byte[] expected = testData.get(r); Assert.assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics final HttpConnectionMetrics cm = conn.getMetrics(); Assert.assertEquals(reqNo, cm.getRequestCount()); Assert.assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } /** * This test case executes a series of simple POST requests using * the 'expect: continue' handshake. */ @Test public void testHttpPostsWithExpectContinue() throws Exception { final int reqNo = 20; final Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { final int size = rnd.nextInt(5000); final byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final byte[] data = EntityUtils.toByteArray(incoming); final ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { final StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); // Activate 'expect: continue' handshake final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); final byte[] data = testData.get(r); final ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); final HttpResponse response = this.client.execute(post, host, conn); final byte[] received = EntityUtils.toByteArray(response.getEntity()); final byte[] expected = testData.get(r); Assert.assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics final HttpConnectionMetrics cm = conn.getMetrics(); Assert.assertEquals(reqNo, cm.getRequestCount()); Assert.assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } /** * This test case executes a series of simple POST requests that do not * meet the target server expectations. */ @Test public void testHttpPostsWithExpectationVerification() throws Exception { final int reqNo = 3; // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } }); this.server.setExpectationVerifier(new HttpExpectationVerifier() { public void verify( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException { final Header someheader = request.getFirstHeader("Secret"); if (someheader != null) { int secretNumber; try { secretNumber = Integer.parseInt(someheader.getValue()); } catch (final NumberFormatException ex) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); return; } if (secretNumber < 2) { response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED); final ByteArrayEntity outgoing = new ByteArrayEntity( EncodingUtils.getAsciiBytes("Wrong secret number")); response.setEntity(outgoing); } } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); post.addHeader("Secret", Integer.toString(r)); final ByteArrayEntity outgoing = new ByteArrayEntity( EncodingUtils.getAsciiBytes("No content " + r)); post.setEntity(outgoing); final HttpResponse response = this.client.execute(post, host, conn); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); EntityUtils.consume(entity); if (r < 2) { Assert.assertEquals(HttpStatus.SC_EXPECTATION_FAILED, response.getStatusLine().getStatusCode()); } else { Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics final HttpConnectionMetrics cm = conn.getMetrics(); Assert.assertEquals(reqNo, cm.getRequestCount()); Assert.assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } static class RepeatingEntity extends AbstractHttpEntity { private final byte[] raw; private final int n; public RepeatingEntity(final String content, final Charset charset, final int n) { super(); final Charset cs = charset != null ? charset : Charset.forName("US-ASCII"); byte[] b; // Java 6 only: // b = content.getBytes(charset); // Java 5 OK: try { b = content.getBytes(cs.name()); } catch (final UnsupportedEncodingException ex) { b = content.getBytes(); } this.raw = b; this.n = n; } public InputStream getContent() throws IOException, IllegalStateException { throw new IllegalStateException("This method is not implemented"); } public long getContentLength() { return (this.raw.length + 2) * this.n; } public boolean isRepeatable() { return true; } public boolean isStreaming() { return false; } public void writeTo(final OutputStream outstream) throws IOException { for (int i = 0; i < this.n; i++) { outstream.write(this.raw); outstream.write('\r'); outstream.write('\n'); } outstream.flush(); } } @Test public void testHttpContent() throws Exception { final String[] patterns = { "0123456789ABCDEF", "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that" }; // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { int n = 1; String s = request.getRequestLine().getUri(); if (s.startsWith("/?n=")) { s = s.substring(4); try { n = Integer.parseInt(s); if (n <= 0) { throw new HttpException("Invalid request: " + "number of repetitions cannot be negative or zero"); } } catch (final NumberFormatException ex) { throw new HttpException("Invalid request: " + "number of repetitions is invalid"); } } final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final String line = EntityUtils.toString(incoming); final ContentType contentType = ContentType.getOrDefault(incoming); Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } final RepeatingEntity outgoing = new RepeatingEntity(line, charset, n); outgoing.setChunked(n % 2 == 0); response.setEntity(outgoing); } else { throw new HttpException("Invalid request: POST request expected"); } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (final String pattern : patterns) { for (int n = 1000; n < 1020; n++) { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest( "POST", "/?n=" + n); final StringEntity outgoing = new StringEntity(pattern); outgoing.setChunked(n % 2 == 0); post.setEntity(outgoing); final HttpResponse response = this.client.execute(post, host, conn); final HttpEntity incoming = response.getEntity(); Assert.assertNotNull(incoming); final InputStream instream = incoming.getContent(); final ContentType contentType = ContentType.getOrDefault(incoming); Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } Assert.assertNotNull(instream); final BufferedReader reader = new BufferedReader(new InputStreamReader(instream, charset)); String line; int count = 0; while ((line = reader.readLine()) != null) { Assert.assertEquals(pattern, line); count++; } Assert.assertEquals(n, count); if (!this.client.keepAlive(response)) { conn.close(); } } } } finally { conn.close(); this.server.shutdown(); } } @Test public void testHttpPostNoEntity() throws Exception { this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final byte[] data = EntityUtils.toByteArray(incoming); final ByteArrayEntity outgoing = new ByteArrayEntity(data); response.setEntity(outgoing); } else { final StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); post.setEntity(null); final HttpResponse response = this.client.execute(post, host, conn); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); final byte[] received = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals(0, received.length); } finally { conn.close(); this.server.shutdown(); } } @Test public void testHttpPostNoContentLength() throws Exception { this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final byte[] data = EntityUtils.toByteArray(incoming); final ByteArrayEntity outgoing = new ByteArrayEntity(data); response.setEntity(outgoing); } else { final StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); post.setEntity(null); this.client = new HttpClient(new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(true) })); final HttpResponse response = this.client.execute(post, host, conn); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); final byte[] received = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals(0, received.length); } finally { conn.close(); this.server.shutdown(); } } @Test public void testHttpPostIdentity() throws Exception { this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final byte[] data = EntityUtils.toByteArray(incoming); final ByteArrayEntity outgoing = new ByteArrayEntity(data); response.setEntity(outgoing); } else { final StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); post.setEntity(null); this.client = new HttpClient(new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { request.addHeader(HTTP.TRANSFER_ENCODING, "identity"); } }, new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(true) })); final HttpResponse response = this.client.execute(post, host, conn); Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); } finally { conn.close(); this.server.shutdown(); } } @Test public void testNoContentResponse() throws Exception { final int reqNo = 20; // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_NO_CONTENT); } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r); final HttpResponse response = this.client.execute(get, host, conn); Assert.assertNull(response.getEntity()); if (!this.client.keepAlive(response)) { conn.close(); Assert.fail("Connection expected to be re-usable"); } } //Verify the connection metrics final HttpConnectionMetrics cm = conn.getMetrics(); Assert.assertEquals(reqNo, cm.getRequestCount()); Assert.assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/0040755 0000000 0000000 00000000000 12276755420 025121 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestHttpEntityWrapper.java0100644 0000000 0000000 00000010172 12276755420 032277 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayOutputStream; import org.apache.http.Consts; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link HttpEntityWrapper}. * */ public class TestHttpEntityWrapper { @Test public void testBasics() throws Exception { final String s = "Message content"; final StringEntity httpentity = new StringEntity(s, ContentType.TEXT_PLAIN); httpentity.setContentEncoding(HTTP.IDENTITY_CODING); final HttpEntityWrapper wrapped = new HttpEntityWrapper(httpentity); Assert.assertEquals(httpentity.getContentLength(), wrapped.getContentLength()); Assert.assertEquals(httpentity.getContentType(), wrapped.getContentType()); Assert.assertEquals(httpentity.getContentEncoding(), wrapped.getContentEncoding()); Assert.assertEquals(httpentity.isChunked(), wrapped.isChunked()); Assert.assertEquals(httpentity.isRepeatable(), wrapped.isRepeatable()); Assert.assertEquals(httpentity.isStreaming(), wrapped.isStreaming()); Assert.assertNotNull(wrapped.getContent()); } @Test public void testIllegalConstructor() throws Exception { try { new HttpEntityWrapper(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testWriteTo() throws Exception { final String s = "Message content"; final byte[] bytes = s.getBytes(Consts.ISO_8859_1.name()); final StringEntity httpentity = new StringEntity(s); final HttpEntityWrapper wrapped = new HttpEntityWrapper(httpentity); ByteArrayOutputStream out = new ByteArrayOutputStream(); wrapped.writeTo(out); byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } out = new ByteArrayOutputStream(); wrapped.writeTo(out); bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } try { wrapped.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testConsumeContent() throws Exception { final String s = "Message content"; final StringEntity httpentity = new StringEntity(s); final HttpEntityWrapper wrapped = new HttpEntityWrapper(httpentity); EntityUtils.consume(wrapped); EntityUtils.consume(wrapped); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestFileEntity.java0100644 0000000 0000000 00000006771 12276755420 030710 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link FileEntity}. * */ public class TestFileEntity { @Test public void testBasics() throws Exception { final File tmpfile = File.createTempFile("testfile", ".txt"); tmpfile.deleteOnExit(); final FileEntity httpentity = new FileEntity(tmpfile, ContentType.TEXT_PLAIN); Assert.assertEquals(tmpfile.length(), httpentity.getContentLength()); final InputStream content = httpentity.getContent(); Assert.assertNotNull(content); content.close(); Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); if (!tmpfile.delete()){ Assert.fail("Failed to delete: "+tmpfile); } } @Test public void testIllegalConstructor() throws Exception { try { new FileEntity(null, ContentType.TEXT_PLAIN); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testWriteTo() throws Exception { final File tmpfile = File.createTempFile("testfile", ".txt"); tmpfile.deleteOnExit(); final FileOutputStream outstream = new FileOutputStream(tmpfile); outstream.write(0); outstream.write(1); outstream.write(2); outstream.write(3); outstream.close(); final FileEntity httpentity = new FileEntity(tmpfile, ContentType.TEXT_PLAIN); final ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); final byte[] bytes = out.toByteArray(); Assert.assertNotNull(bytes); Assert.assertEquals(tmpfile.length(), bytes.length); for (int i = 0; i < 4; i++) { Assert.assertEquals(i, bytes[i]); } if (!tmpfile.delete()){ Assert.fail("Failed to delete: "+tmpfile); } try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestBufferedHttpEntity.java0100644 0000000 0000000 00000013032 12276755420 032377 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import org.apache.http.Consts; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link BufferedHttpEntity}. * */ public class TestBufferedHttpEntity { @Test public void testBufferingEntity() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final InputStreamEntity httpentity = new InputStreamEntity(new ByteArrayInputStream(bytes), -1); final BufferedHttpEntity bufentity = new BufferedHttpEntity(httpentity); Assert.assertEquals(bytes.length, bufentity.getContentLength()); Assert.assertTrue(bufentity.isRepeatable()); Assert.assertFalse(bufentity.isChunked()); Assert.assertFalse(bufentity.isStreaming()); // test if we can obtain contain multiple times Assert.assertNotNull(bufentity.getContent ()); Assert.assertNotNull(bufentity.getContent ()); } @Test public void testWrappingEntity() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final ByteArrayEntity httpentity = new ByteArrayEntity(bytes); httpentity.setChunked(true); final BufferedHttpEntity bufentity = new BufferedHttpEntity(httpentity); Assert.assertEquals(bytes.length, bufentity.getContentLength()); Assert.assertTrue(bufentity.isRepeatable()); Assert.assertTrue(bufentity.isChunked()); Assert.assertFalse(bufentity.isStreaming()); // test if we can obtain contain multiple times Assert.assertNotNull(bufentity.getContent ()); Assert.assertNotNull(bufentity.getContent ()); } @Test public void testIllegalConstructor() throws Exception { try { new BufferedHttpEntity(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testWriteToBuffered() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final InputStreamEntity httpentity = new InputStreamEntity(new ByteArrayInputStream(bytes), -1); final BufferedHttpEntity bufentity = new BufferedHttpEntity(httpentity); ByteArrayOutputStream out = new ByteArrayOutputStream(); bufentity.writeTo(out); byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } out = new ByteArrayOutputStream(); bufentity.writeTo(out); bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } try { bufentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testWriteToWrapped() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final ByteArrayEntity httpentity = new ByteArrayEntity(bytes); final BufferedHttpEntity bufentity = new BufferedHttpEntity(httpentity); ByteArrayOutputStream out = new ByteArrayOutputStream(); bufentity.writeTo(out); byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } out = new ByteArrayOutputStream(); bufentity.writeTo(out); bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } try { bufentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestContentType.java0100644 0000000 0000000 00000017215 12276755420 031103 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.nio.charset.Charset; import org.apache.http.Header; import org.apache.http.ParseException; import org.apache.http.message.BasicHeader; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link ContentType}. * */ public class TestContentType { @Test public void testBasis() throws Exception { final ContentType contentType = ContentType.create("text/plain", "US-ASCII"); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("US-ASCII", contentType.getCharset().name()); Assert.assertEquals("text/plain; charset=US-ASCII", contentType.toString()); } @Test public void testWithCharset() throws Exception { ContentType contentType = ContentType.create("text/plain", "US-ASCII"); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("US-ASCII", contentType.getCharset().name()); Assert.assertEquals("text/plain; charset=US-ASCII", contentType.toString()); contentType = contentType.withCharset(Charset.forName("UTF-8")); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("UTF-8", contentType.getCharset().name()); Assert.assertEquals("text/plain; charset=UTF-8", contentType.toString()); } @Test public void testWithCharsetString() throws Exception { ContentType contentType = ContentType.create("text/plain", "US-ASCII"); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("US-ASCII", contentType.getCharset().name()); Assert.assertEquals("text/plain; charset=US-ASCII", contentType.toString()); contentType = contentType.withCharset("UTF-8"); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("UTF-8", contentType.getCharset().name()); Assert.assertEquals("text/plain; charset=UTF-8", contentType.toString()); } @Test public void testLowCaseText() throws Exception { final ContentType contentType = ContentType.create("Text/Plain", "ascii"); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("US-ASCII", contentType.getCharset().name()); } @Test public void testCreateInvalidInput() throws Exception { try { ContentType.create(null, (String) null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { ContentType.create(" ", (String) null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { ContentType.create("stuff;", (String) null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { ContentType.create("text/plain", ","); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testParse() throws Exception { final ContentType contentType = ContentType.parse("text/plain; charset=\"ascii\""); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("US-ASCII", contentType.getCharset().name()); Assert.assertEquals("text/plain; charset=ascii", contentType.toString()); } @Test public void testParseMultiparam() throws Exception { final ContentType contentType = ContentType.parse("text/plain; charset=\"ascii\"; " + "p0 ; p1 = \"blah-blah\" ; p2 = \" yada yada \" "); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("US-ASCII", contentType.getCharset().name()); Assert.assertEquals("text/plain; charset=ascii; p0; p1=blah-blah; p2=\" yada yada \"", contentType.toString()); Assert.assertEquals(null, contentType.getParameter("p0")); Assert.assertEquals("blah-blah", contentType.getParameter("p1")); Assert.assertEquals(" yada yada ", contentType.getParameter("p2")); Assert.assertEquals(null, contentType.getParameter("p3")); } @Test public void testParseEmptyCharset() throws Exception { final ContentType contentType = ContentType.parse("text/plain; charset=\" \""); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals(null, contentType.getCharset()); } @Test public void testParseInvalidInput() throws Exception { try { ContentType.parse(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { ContentType.parse(";"); Assert.fail("ParseException should have been thrown"); } catch (final ParseException ex) { // expected } } @Test public void testExtractNullInput() throws Exception { Assert.assertNull(ContentType.get(null)); } @Test public void testExtractNullContentType() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContentType((Header)null); Assert.assertNull(ContentType.get(httpentity)); } @Test public void testExtract() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContentType(new BasicHeader("Content-Type", "text/plain; charset = UTF-8")); final ContentType contentType = ContentType.get(httpentity); Assert.assertNotNull(contentType); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals("UTF-8", contentType.getCharset().name()); } @Test public void testExtractNoCharset() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContentType(new BasicHeader("Content-Type", "text/plain; param=yadayada")); final ContentType contentType = ContentType.get(httpentity); Assert.assertNotNull(contentType); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertNull(contentType.getCharset()); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestSerializableEntity.java0100644 0000000 0000000 00000012210 12276755420 032420 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.junit.Assert; import org.junit.Test; public class TestSerializableEntity { public static class SerializableObject implements Serializable { private static final long serialVersionUID = 1833335861188359573L; public int intValue = 4; public String stringValue = "Hello"; public SerializableObject() {} } @Test public void testBasicsBuff() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); final Serializable serializableObj = new SerializableObject(); out.writeObject(serializableObj); final SerializableEntity httpentity = new SerializableEntity(serializableObj, true); Assert.assertEquals(baos.toByteArray().length, httpentity.getContentLength()); Assert.assertNotNull(httpentity.getContent()); Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); } @Test public void testBasicsDirect() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); final Serializable serializableObj = new SerializableObject(); out.writeObject(serializableObj); final SerializableEntity httpentity = new SerializableEntity(serializableObj, false); Assert.assertEquals(-1, httpentity.getContentLength()); Assert.assertNotNull(httpentity.getContent()); Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); } @Test public void testIllegalConstructor() throws Exception { try { new SerializableEntity(null, false); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testWriteToBuff() throws Exception { final Serializable serializableObj = new SerializableObject(); final SerializableEntity httpentity = new SerializableEntity(serializableObj, true); final ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); final byte[] bytes = out.toByteArray(); Assert.assertNotNull(bytes); final ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream( bytes)); final SerializableObject serIn = (SerializableObject) oin.readObject(); Assert.assertEquals(4, serIn.intValue); Assert.assertEquals("Hello", serIn.stringValue); try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testWriteToDirect() throws Exception { final Serializable serializableObj = new SerializableObject(); final SerializableEntity httpentity = new SerializableEntity(serializableObj, false); final ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); final byte[] bytes = out.toByteArray(); Assert.assertNotNull(bytes); final ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream( bytes)); final SerializableObject serIn = (SerializableObject) oin.readObject(); Assert.assertEquals(4, serIn.intValue); Assert.assertEquals("Hello", serIn.stringValue); try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestEntityTemplate.java0100644 0000000 0000000 00000006757 12276755420 031610 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.HttpEntity; import org.apache.http.util.EntityUtils; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link EntityTemplate}. */ public class TestEntityTemplate { @Test public void testBasics() throws Exception { final HttpEntity httpentity = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { outstream.write('a'); } }); Assert.assertEquals(-1, httpentity.getContentLength()); Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); } @Test public void testIllegalConstructor() throws Exception { try { new EntityTemplate(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testWriteTo() throws Exception { final HttpEntity httpentity = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { outstream.write('a'); } }); final ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); final byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(1, bytes2.length); try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testgetContent() throws Exception { final HttpEntity httpentity = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { outstream.write('a'); } }); final InputStream instream = httpentity.getContent(); Assert.assertNotNull(instream); final String s = EntityUtils.toString(httpentity); Assert.assertEquals("a", s); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestAbstractHttpEntity.java0100644 0000000 0000000 00000006517 12276755420 032432 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link AbstractHttpEntity}. * */ public class TestAbstractHttpEntity { @Test public void testContentType() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "blah")); Assert.assertEquals(HTTP.CONTENT_TYPE, httpentity.getContentType().getName()); Assert.assertEquals("blah", httpentity.getContentType().getValue()); httpentity.setContentType("blah"); Assert.assertEquals(HTTP.CONTENT_TYPE, httpentity.getContentType().getName()); Assert.assertEquals("blah", httpentity.getContentType().getValue()); httpentity.setContentType((Header)null); Assert.assertNull(httpentity.getContentType()); httpentity.setContentType((String)null); Assert.assertNull(httpentity.getContentType()); } @Test public void testContentEncoding() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "gzip")); Assert.assertEquals(HTTP.CONTENT_ENCODING, httpentity.getContentEncoding().getName()); Assert.assertEquals("gzip", httpentity.getContentEncoding().getValue()); httpentity.setContentEncoding("gzip"); Assert.assertEquals(HTTP.CONTENT_ENCODING, httpentity.getContentEncoding().getName()); Assert.assertEquals("gzip", httpentity.getContentEncoding().getValue()); httpentity.setContentEncoding((Header)null); Assert.assertNull(httpentity.getContentEncoding()); httpentity.setContentEncoding((String)null); Assert.assertNull(httpentity.getContentEncoding()); } @Test public void testChunkingFlag() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); Assert.assertFalse(httpentity.isChunked()); httpentity.setChunked(true); Assert.assertTrue(httpentity.isChunked()); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestBasicHttpEntity.java0100644 0000000 0000000 00000007747 12276755420 031716 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import org.apache.http.Consts; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link BasicHttpEntity}. * */ public class TestBasicHttpEntity { @Test public void testBasics() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final InputStream content = new ByteArrayInputStream(bytes); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(content); httpentity.setContentLength(bytes.length); Assert.assertEquals(bytes.length, httpentity.getContentLength()); Assert.assertFalse(httpentity.isRepeatable()); Assert.assertTrue(httpentity.isStreaming()); } @Test public void testContent() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final InputStream content = new ByteArrayInputStream(bytes); final BasicHttpEntity httpentity = new BasicHttpEntity(); try { httpentity.getContent(); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException ex) { // expected } httpentity.setContent(content); Assert.assertEquals(content, httpentity.getContent()); httpentity.setContent(null); try { httpentity.getContent(); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException ex) { // expected } } @Test public void testWriteTo() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final InputStream content = new ByteArrayInputStream(bytes); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(content); ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); final byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } httpentity.setContent(null); out = new ByteArrayOutputStream(); try { httpentity.writeTo(out); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException ex) { // expected } try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestByteArrayEntity.java0100644 0000000 0000000 00000012647 12276755420 031732 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayOutputStream; import org.apache.http.Consts; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link ByteArrayEntity}. * */ public class TestByteArrayEntity { @Test public void testBasics() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final ByteArrayEntity httpentity = new ByteArrayEntity(bytes); Assert.assertEquals(bytes.length, httpentity.getContentLength()); Assert.assertNotNull(httpentity.getContent()); Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); } @Test public void testBasicOffLen() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final ByteArrayEntity httpentity = new ByteArrayEntity(bytes, 8, 7); Assert.assertEquals(7, httpentity.getContentLength()); Assert.assertNotNull(httpentity.getContent()); Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); } @Test(expected=IllegalArgumentException.class) public void testIllegalConstructorNullByteArray() throws Exception { new ByteArrayEntity(null); } @Test(expected=IndexOutOfBoundsException.class) public void testIllegalConstructorBadLen() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); new ByteArrayEntity(bytes, 0, bytes.length + 1); } @Test(expected=IndexOutOfBoundsException.class) public void testIllegalConstructorBadOff1() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); new ByteArrayEntity(bytes, -1, bytes.length); } @Test(expected=IndexOutOfBoundsException.class) public void testIllegalConstructorBadOff2() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); new ByteArrayEntity(bytes, bytes.length + 1, bytes.length); } @Test public void testWriteTo() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final ByteArrayEntity httpentity = new ByteArrayEntity(bytes); ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } out = new ByteArrayOutputStream(); httpentity.writeTo(out); bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testWriteToOffLen() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII.name()); final int off = 8; final int len = 7; final ByteArrayEntity httpentity = new ByteArrayEntity(bytes, off, len); ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(len, bytes2.length); for (int i = 0; i < len; i++) { Assert.assertEquals(bytes[i+off], bytes2[i]); } out = new ByteArrayOutputStream(); httpentity.writeTo(out); bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(len, bytes2.length); for (int i = 0; i < len; i++) { Assert.assertEquals(bytes[i+off], bytes2[i]); } try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestInputStreamEntity.java0100644 0000000 0000000 00000012060 12276755420 032270 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import org.apache.http.Consts; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link InputStreamEntity}. * */ public class TestInputStreamEntity { @Test public void testBasics() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ISO_8859_1.name()); final InputStream instream = new ByteArrayInputStream(bytes); final InputStreamEntity httpentity = new InputStreamEntity(instream, bytes.length); Assert.assertEquals(bytes.length, httpentity.getContentLength()); Assert.assertEquals(instream, httpentity.getContent()); Assert.assertNotNull(httpentity.getContent()); Assert.assertFalse(httpentity.isRepeatable()); Assert.assertTrue(httpentity.isStreaming()); } @Test(expected = IllegalArgumentException.class) public void testIllegalConstructor() throws Exception { new InputStreamEntity(null, 0); } @Test public void testUnknownLengthConstructor() throws Exception { final InputStream instream = new ByteArrayInputStream(new byte[0]); final InputStreamEntity httpentity = new InputStreamEntity(instream); Assert.assertEquals(-1, httpentity.getContentLength()); } @Test public void testWriteTo() throws Exception { final String message = "Message content"; final byte[] bytes = message.getBytes(Consts.ISO_8859_1.name()); final InputStream instream = new ByteArrayInputStream(bytes); final InputStreamEntity httpentity = new InputStreamEntity(instream, bytes.length); final ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); final byte[] writtenBytes = out.toByteArray(); Assert.assertNotNull(writtenBytes); Assert.assertEquals(bytes.length, writtenBytes.length); final String s = new String(writtenBytes, Consts.ISO_8859_1.name()); Assert.assertEquals(message, s); } @Test public void testWriteToPartialContent() throws Exception { final String message = "Message content"; final byte[] bytes = message.getBytes(Consts.ISO_8859_1.name()); final InputStream instream = new ByteArrayInputStream(bytes); final int contentLength = 7; final InputStreamEntity httpentity = new InputStreamEntity(instream, contentLength); final ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); final byte[] writtenBytes = out.toByteArray(); Assert.assertNotNull(writtenBytes); Assert.assertEquals(contentLength, writtenBytes.length); final String s = new String(writtenBytes, Consts.ISO_8859_1.name()); Assert.assertEquals(message.substring(0, contentLength), s); } @Test public void testWriteToUnknownLength() throws Exception { final String message = "Message content"; final byte[] bytes = message.getBytes(Consts.ISO_8859_1.name()); final InputStream instream = new ByteArrayInputStream(bytes); final InputStreamEntity httpentity = new InputStreamEntity(instream); final ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); final byte[] writtenBytes = out.toByteArray(); Assert.assertNotNull(writtenBytes); Assert.assertEquals(bytes.length, writtenBytes.length); final String s = new String(writtenBytes, Consts.ISO_8859_1.name()); Assert.assertEquals(message, s); } @Test(expected = IllegalArgumentException.class) public void testWriteToNull() throws Exception { final InputStream instream = new ByteArrayInputStream(new byte[0]); final InputStreamEntity httpentity = new InputStreamEntity(instream, 0); httpentity.writeTo(null); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/entity/TestStringEntity.java0100644 0000000 0000000 00000013122 12276755420 031263 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.entity; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; import org.apache.http.Consts; import org.apache.http.util.EntityUtils; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link StringEntity}. */ public class TestStringEntity { @Test public void testBasics() throws Exception { final String s = "Message content"; final StringEntity httpentity = new StringEntity(s, ContentType.TEXT_PLAIN); final byte[] bytes = s.getBytes(Consts.ISO_8859_1.name()); Assert.assertEquals(bytes.length, httpentity.getContentLength()); Assert.assertNotNull(httpentity.getContent()); Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); } @Test public void testIllegalConstructor() throws Exception { try { new StringEntity(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testDefaultContent() throws Exception { final String s = "Message content"; StringEntity httpentity = new StringEntity(s, ContentType.create("text/csv", "ANSI_X3.4-1968")); Assert.assertEquals("text/csv; charset=US-ASCII", httpentity.getContentType().getValue()); httpentity = new StringEntity(s, Consts.ASCII.name()); Assert.assertEquals("text/plain; charset=US-ASCII", httpentity.getContentType().getValue()); httpentity = new StringEntity(s, Consts.ASCII); Assert.assertEquals("text/plain; charset=US-ASCII", httpentity.getContentType().getValue()); httpentity = new StringEntity(s); Assert.assertEquals("text/plain; charset=ISO-8859-1", httpentity.getContentType().getValue()); } private static String constructString(final int [] unicodeChars) { final StringBuilder buffer = new StringBuilder(); if (unicodeChars != null) { for (final int unicodeChar : unicodeChars) { buffer.append((char)unicodeChar); } } return buffer.toString(); } static final int SWISS_GERMAN_HELLO [] = { 0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4 }; @Test public void testNullCharset() throws Exception { final String s = constructString(SWISS_GERMAN_HELLO); StringEntity httpentity = new StringEntity(s, ContentType.create("text/plain", (Charset) null)); Assert.assertNotNull(httpentity.getContentType()); Assert.assertEquals("text/plain", httpentity.getContentType().getValue()); Assert.assertEquals(s, EntityUtils.toString(httpentity)); httpentity = new StringEntity(s, (Charset) null); Assert.assertNotNull(httpentity.getContentType()); Assert.assertEquals("text/plain", httpentity.getContentType().getValue()); Assert.assertEquals(s, EntityUtils.toString(httpentity)); httpentity = new StringEntity(s, (String) null); Assert.assertNotNull(httpentity.getContentType()); Assert.assertEquals("text/plain", httpentity.getContentType().getValue()); Assert.assertEquals(s, EntityUtils.toString(httpentity)); } @Test public void testWriteTo() throws Exception { final String s = "Message content"; final byte[] bytes = s.getBytes(Consts.ISO_8859_1.name()); final StringEntity httpentity = new StringEntity(s); ByteArrayOutputStream out = new ByteArrayOutputStream(); httpentity.writeTo(out); byte[] bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } out = new ByteArrayOutputStream(); httpentity.writeTo(out); bytes2 = out.toByteArray(); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } try { httpentity.writeTo(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/0040755 0000000 0000000 00000000000 12276755421 024547 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestBasicRequest.java0100644 0000000 0000000 00000004654 12276755420 030651 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.apache.http.HttpRequest; import org.apache.http.HttpVersion; import org.apache.http.message.BasicHttpRequest; import org.junit.Assert; import org.junit.Test; public class TestBasicRequest { @Test public void testConstructor() throws Exception { new BasicHttpRequest("GET", "/stuff"); new BasicHttpRequest("GET", "/stuff", HttpVersion.HTTP_1_1); try { new BasicHttpRequest(null, "/stuff"); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new BasicHttpRequest("GET", null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testRequestLine() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/stuff", HttpVersion.HTTP_1_0); Assert.assertEquals("GET", request.getRequestLine().getMethod()); Assert.assertEquals("/stuff", request.getRequestLine().getUri()); Assert.assertEquals(HttpVersion.HTTP_1_0, request.getRequestLine().getProtocolVersion()); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/SessionOutputBufferMock.java0100644 0000000 0000000 00000005673 12276755420 032231 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.io.SessionOutputBufferImpl; /** * {@link org.apache.http.io.SessionOutputBuffer} mockup implementation. * */ public class SessionOutputBufferMock extends SessionOutputBufferImpl { public static final int BUFFER_SIZE = 16; private final ByteArrayOutputStream buffer; public SessionOutputBufferMock( final ByteArrayOutputStream buffer, final int buffersize, final int fragementSizeHint, final CharsetEncoder encoder) { super(new HttpTransportMetricsImpl(), buffersize, fragementSizeHint, encoder); bind(buffer); this.buffer = buffer; } public SessionOutputBufferMock( final ByteArrayOutputStream buffer, final int buffersize) { this(buffer, buffersize, buffersize, null); } public SessionOutputBufferMock( final CharsetEncoder encoder) { this(new ByteArrayOutputStream(), BUFFER_SIZE, BUFFER_SIZE, encoder); } public SessionOutputBufferMock( final Charset charset) { this(new ByteArrayOutputStream(), BUFFER_SIZE, BUFFER_SIZE, charset != null ? charset.newEncoder() : null); } public SessionOutputBufferMock(final ByteArrayOutputStream buffer) { this(buffer, BUFFER_SIZE, BUFFER_SIZE, null); } public SessionOutputBufferMock() { this(new ByteArrayOutputStream()); } public byte[] getData() { if (this.buffer != null) { return this.buffer.toByteArray(); } else { return new byte[] {}; } } } ././@LongLink0100644 0000000 0000000 00000000154 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestDefaultBHttpServerConnection.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestDefaultBHttpServerConnecti0100644 0000000 0000000 00000016333 12276755421 032535 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.net.Socket; import junit.framework.Assert; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.io.DefaultHttpRequestParserFactory; import org.apache.http.impl.io.DefaultHttpResponseWriterFactory; import org.apache.http.message.BasicHttpResponse; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class TestDefaultBHttpServerConnection { @Mock private Socket socket; private DefaultBHttpServerConnection conn; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); conn = new DefaultBHttpServerConnection(1024, 1024, null, null, MessageConstraints.DEFAULT, LaxContentLengthStrategy.INSTANCE, StrictContentLengthStrategy.INSTANCE, DefaultHttpRequestParserFactory.INSTANCE, DefaultHttpResponseWriterFactory.INSTANCE); } @Test public void testBasics() throws Exception { Assert.assertFalse(conn.isOpen()); Assert.assertEquals("[Not bound]", conn.toString()); } @Test public void testReadRequestHead() throws Exception { final String s = "GET / HTTP/1.1\r\nUser-Agent: test\r\n\r\n"; final ByteArrayInputStream instream = new ByteArrayInputStream(s.getBytes("ASCII")); Mockito.when(socket.getInputStream()).thenReturn(instream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getRequestCount()); final HttpRequest request = conn.receiveRequestHeader(); Assert.assertNotNull(request); Assert.assertEquals(HttpVersion.HTTP_1_1, request.getProtocolVersion()); Assert.assertEquals("/", request.getRequestLine().getUri()); Assert.assertEquals("GET", request.getRequestLine().getMethod()); Assert.assertTrue(request.containsHeader("User-Agent")); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); } @Test public void testReadRequestEntity() throws Exception { final String s = "POST / HTTP/1.1\r\nUser-Agent: test\r\nContent-Length: 3\r\n\r\n123"; final ByteArrayInputStream instream = new ByteArrayInputStream(s.getBytes("ASCII")); Mockito.when(socket.getInputStream()).thenReturn(instream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getRequestCount()); final HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) conn.receiveRequestHeader(); Assert.assertNotNull(request); Assert.assertEquals(HttpVersion.HTTP_1_1, request.getProtocolVersion()); Assert.assertEquals("/", request.getRequestLine().getUri()); Assert.assertEquals("POST", request.getRequestLine().getMethod()); Assert.assertTrue(request.containsHeader("User-Agent")); Assert.assertNull(request.getEntity()); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); conn.receiveRequestEntity(request); final HttpEntity entity = request.getEntity(); Assert.assertNotNull(entity); Assert.assertEquals(3, entity.getContentLength()); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); } @Test public void testWriteResponseHead() throws Exception { final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(outstream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("User-Agent", "test"); conn.sendResponseHeader(response); conn.flush(); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); final String s = new String(outstream.toByteArray(), "ASCII"); Assert.assertEquals("HTTP/1.1 200 OK\r\nUser-Agent: test\r\n\r\n", s); } @Test public void testWriteResponse100Head() throws Exception { final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(outstream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Go on"); conn.sendResponseHeader(response); conn.flush(); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); final String s = new String(outstream.toByteArray(), "ASCII"); Assert.assertEquals("HTTP/1.1 100 Go on\r\n\r\n", s); } @Test public void testWriteResponseEntity() throws Exception { final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(outstream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("User-Agent", "test"); response.addHeader("Content-Length", "3"); response.setEntity(new StringEntity("123", ContentType.TEXT_PLAIN)); conn.sendResponseHeader(response); conn.sendResponseEntity(response); conn.flush(); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); final String s = new String(outstream.toByteArray(), "ASCII"); Assert.assertEquals("HTTP/1.1 200 OK\r\nUser-Agent: test\r\nContent-Length: 3\r\n\r\n123", s); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestBHttpConnectionBase.java0100644 0000000 0000000 00000035161 12276755420 032110 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import junit.framework.Assert; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.io.ChunkedInputStream; import org.apache.http.impl.io.ChunkedOutputStream; import org.apache.http.impl.io.ContentLengthInputStream; import org.apache.http.impl.io.ContentLengthOutputStream; import org.apache.http.impl.io.IdentityInputStream; import org.apache.http.impl.io.IdentityOutputStream; import org.apache.http.message.BasicHttpResponse; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class TestBHttpConnectionBase { @Mock private Socket socket; private BHttpConnectionBase conn; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); conn = new BHttpConnectionBase(1024, 1024, null, null, MessageConstraints.DEFAULT, LaxContentLengthStrategy.INSTANCE, StrictContentLengthStrategy.INSTANCE); } @Test public void testBasics() throws Exception { Assert.assertFalse(conn.isOpen()); Assert.assertEquals(-1, conn.getLocalPort()); Assert.assertEquals(-1, conn.getRemotePort()); Assert.assertEquals(null, conn.getLocalAddress()); Assert.assertEquals(null, conn.getRemoteAddress()); Assert.assertEquals("[Not bound]", conn.toString()); } @Test public void testSocketBind() throws Exception { final InetAddress localAddress = InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); final int localPort = 8888; final InetAddress remoteAddress = InetAddress.getByAddress(new byte[] {10, 0, 0, 2}); final int remotePort = 80; final InetSocketAddress localSockAddress = new InetSocketAddress(localAddress, localPort); final InetSocketAddress remoteSockAddress = new InetSocketAddress(remoteAddress, remotePort); Mockito.when(socket.getLocalSocketAddress()).thenReturn(localSockAddress); Mockito.when(socket.getRemoteSocketAddress()).thenReturn(remoteSockAddress); Mockito.when(socket.getLocalAddress()).thenReturn(localAddress); Mockito.when(socket.getLocalPort()).thenReturn(localPort); Mockito.when(socket.getInetAddress()).thenReturn(remoteAddress); Mockito.when(socket.getPort()).thenReturn(remotePort); conn.bind(socket); Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString()); Assert.assertTrue(conn.isOpen()); Assert.assertEquals(8888, conn.getLocalPort()); Assert.assertEquals(80, conn.getRemotePort()); Assert.assertEquals(InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), conn.getLocalAddress()); Assert.assertEquals(InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), conn.getRemoteAddress()); } @Test public void testConnectionClose() throws Exception { final InputStream instream = Mockito.mock(InputStream.class); final OutputStream outstream = Mockito.mock(OutputStream.class); Mockito.when(socket.getInputStream()).thenReturn(instream); Mockito.when(socket.getOutputStream()).thenReturn(outstream); conn.bind(socket); conn.ensureOpen(); conn.getSessionOutputBuffer().write(0); Assert.assertTrue(conn.isOpen()); conn.close(); Assert.assertFalse(conn.isOpen()); Mockito.verify(outstream, Mockito.times(1)).write( Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); Mockito.verify(socket, Mockito.times(1)).shutdownInput(); Mockito.verify(socket, Mockito.times(1)).shutdownOutput(); Mockito.verify(socket, Mockito.times(1)).close(); conn.close(); Mockito.verify(socket, Mockito.times(1)).close(); Mockito.verify(outstream, Mockito.times(1)).write( Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); } @Test public void testConnectionShutdown() throws Exception { final InputStream instream = Mockito.mock(InputStream.class); final OutputStream outstream = Mockito.mock(OutputStream.class); Mockito.when(socket.getInputStream()).thenReturn(instream); Mockito.when(socket.getOutputStream()).thenReturn(outstream); conn.bind(socket); conn.ensureOpen(); conn.getSessionOutputBuffer().write(0); Assert.assertTrue(conn.isOpen()); conn.shutdown(); Assert.assertFalse(conn.isOpen()); Mockito.verify(outstream, Mockito.never()).write( Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); Mockito.verify(socket, Mockito.never()).shutdownInput(); Mockito.verify(socket, Mockito.never()).shutdownOutput(); Mockito.verify(socket, Mockito.times(1)).close(); conn.close(); Mockito.verify(socket, Mockito.times(1)).close(); conn.shutdown(); Mockito.verify(socket, Mockito.times(2)).close(); } @Test public void testPrepareInputLengthDelimited() throws Exception { final HttpResponse message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); message.addHeader("Content-Length", "10"); message.addHeader("Content-Type", "stuff"); message.addHeader("Content-Encoding", "identity"); final HttpEntity entity = conn.prepareInput(message); Assert.assertNotNull(entity); Assert.assertFalse(entity.isChunked()); Assert.assertEquals(10, entity.getContentLength()); final Header ct = entity.getContentType(); Assert.assertNotNull(ct); Assert.assertEquals("stuff", ct.getValue()); final Header ce = entity.getContentEncoding(); Assert.assertNotNull(ce); Assert.assertEquals("identity", ce.getValue()); final InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue((instream instanceof ContentLengthInputStream)); } @Test public void testPrepareInputChunked() throws Exception { final HttpResponse message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); message.addHeader("Transfer-Encoding", "chunked"); final HttpEntity entity = conn.prepareInput(message); Assert.assertNotNull(entity); Assert.assertTrue(entity.isChunked()); Assert.assertEquals(-1, entity.getContentLength()); final InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue((instream instanceof ChunkedInputStream)); } @Test public void testPrepareInputIdentity() throws Exception { final HttpResponse message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final HttpEntity entity = conn.prepareInput(message); Assert.assertNotNull(entity); Assert.assertFalse(entity.isChunked()); Assert.assertEquals(-1, entity.getContentLength()); final InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue((instream instanceof IdentityInputStream)); } @Test public void testPrepareOutputLengthDelimited() throws Exception { final HttpResponse message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); message.addHeader("Content-Length", "10"); final OutputStream outstream = conn.prepareOutput(message); Assert.assertNotNull(outstream); Assert.assertTrue((outstream instanceof ContentLengthOutputStream)); } @Test public void testPrepareOutputChunked() throws Exception { final HttpResponse message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); message.addHeader("Transfer-Encoding", "chunked"); final OutputStream outstream = conn.prepareOutput(message); Assert.assertNotNull(outstream); Assert.assertTrue((outstream instanceof ChunkedOutputStream)); } @Test public void testPrepareOutputIdentity() throws Exception { final HttpResponse message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final OutputStream outstream = conn.prepareOutput(message); Assert.assertNotNull(outstream); Assert.assertTrue((outstream instanceof IdentityOutputStream)); } @Test public void testSetSocketTimeout() throws Exception { conn.bind(socket); conn.setSocketTimeout(123); Mockito.verify(socket, Mockito.times(1)).setSoTimeout(123); } @Test public void testSetSocketTimeoutException() throws Exception { conn.bind(socket); Mockito.doThrow(new SocketException()).when(socket).setSoTimeout(Mockito.anyInt()); conn.setSocketTimeout(123); Mockito.verify(socket, Mockito.times(1)).setSoTimeout(123); } @Test public void testGetSocketTimeout() throws Exception { Assert.assertEquals(-1, conn.getSocketTimeout()); Mockito.when(socket.getSoTimeout()).thenReturn(345); conn.bind(socket); Assert.assertEquals(345, conn.getSocketTimeout()); } @Test public void testGetSocketTimeoutException() throws Exception { Assert.assertEquals(-1, conn.getSocketTimeout()); Mockito.when(socket.getSoTimeout()).thenThrow(new SocketException()); conn.bind(socket); Assert.assertEquals(-1, conn.getSocketTimeout()); } @Test public void testAwaitInputInBuffer() throws Exception { final ByteArrayInputStream instream = Mockito.spy(new ByteArrayInputStream( new byte[] {1, 2, 3, 4, 5})); Mockito.when(socket.getInputStream()).thenReturn(instream); conn.bind(socket); conn.ensureOpen(); conn.getSessionInputBuffer().read(); Assert.assertTrue(conn.awaitInput(432)); Mockito.verify(socket, Mockito.never()).setSoTimeout(Mockito.anyInt()); Mockito.verify(instream, Mockito.times(1)).read( Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); } @Test public void testAwaitInputInSocket() throws Exception { final ByteArrayInputStream instream = Mockito.spy(new ByteArrayInputStream( new byte[] {1, 2, 3, 4, 5})); Mockito.when(socket.getInputStream()).thenReturn(instream); Mockito.when(socket.getSoTimeout()).thenReturn(345); conn.bind(socket); conn.ensureOpen(); Assert.assertTrue(conn.awaitInput(432)); Mockito.verify(socket, Mockito.times(1)).setSoTimeout(432); Mockito.verify(socket, Mockito.times(1)).setSoTimeout(345); Mockito.verify(instream, Mockito.times(1)).read( Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); } @Test public void testAwaitInputNoData() throws Exception { final InputStream instream = Mockito.mock(InputStream.class); Mockito.when(socket.getInputStream()).thenReturn(instream); Mockito.when(instream.read(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())) .thenReturn(-1); conn.bind(socket); conn.ensureOpen(); Assert.assertFalse(conn.awaitInput(432)); } @Test public void testStaleWhenClosed() throws Exception { conn.bind(socket); conn.ensureOpen(); conn.close(); Assert.assertTrue(conn.isStale()); } @Test public void testNotStaleWhenHasData() throws Exception { final ByteArrayInputStream instream = Mockito.spy(new ByteArrayInputStream( new byte[] {1, 2, 3, 4, 5})); Mockito.when(socket.getInputStream()).thenReturn(instream); conn.bind(socket); conn.ensureOpen(); Assert.assertFalse(conn.isStale()); } @Test public void testStaleWhenEndOfStream() throws Exception { final InputStream instream = Mockito.mock(InputStream.class); Mockito.when(socket.getInputStream()).thenReturn(instream); Mockito.when(instream.read(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())) .thenReturn(-1); conn.bind(socket); conn.ensureOpen(); Assert.assertTrue(conn.isStale()); } @Test public void testNotStaleWhenTimeout() throws Exception { final InputStream instream = Mockito.mock(InputStream.class); Mockito.when(socket.getInputStream()).thenReturn(instream); Mockito.when(instream.read(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())) .thenThrow(new SocketTimeoutException()); conn.bind(socket); conn.ensureOpen(); Assert.assertFalse(conn.isStale()); } @Test public void testStaleWhenIOError() throws Exception { final InputStream instream = Mockito.mock(InputStream.class); Mockito.when(socket.getInputStream()).thenReturn(instream); Mockito.when(instream.read(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())) .thenThrow(new SocketException()); conn.bind(socket); conn.ensureOpen(); Assert.assertTrue(conn.isStale()); } } ././@LongLink0100644 0000000 0000000 00000000154 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestDefaultBHttpClientConnection.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestDefaultBHttpClientConnecti0100644 0000000 0000000 00000014707 12276755421 032510 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.net.Socket; import junit.framework.Assert; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.io.DefaultHttpRequestWriterFactory; import org.apache.http.impl.io.DefaultHttpResponseParserFactory; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class TestDefaultBHttpClientConnection { @Mock private Socket socket; private DefaultBHttpClientConnection conn; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); conn = new DefaultBHttpClientConnection(1024, 1024, null, null, MessageConstraints.DEFAULT, LaxContentLengthStrategy.INSTANCE, StrictContentLengthStrategy.INSTANCE, DefaultHttpRequestWriterFactory.INSTANCE, DefaultHttpResponseParserFactory.INSTANCE); } @Test public void testBasics() throws Exception { Assert.assertFalse(conn.isOpen()); Assert.assertEquals("[Not bound]", conn.toString()); } @Test public void testReadRequestHead() throws Exception { final String s = "HTTP/1.1 200 OK\r\nUser-Agent: test\r\n\r\n"; final ByteArrayInputStream instream = new ByteArrayInputStream(s.getBytes("ASCII")); Mockito.when(socket.getInputStream()).thenReturn(instream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); final HttpResponse response = conn.receiveResponseHeader(); Assert.assertNotNull(response); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader("User-Agent")); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); } @Test public void testReadRequestEntity() throws Exception { final String s = "HTTP/1.1 200 OK\r\nUser-Agent: test\r\nContent-Length: 3\r\n\r\n123"; final ByteArrayInputStream instream = new ByteArrayInputStream(s.getBytes("ASCII")); Mockito.when(socket.getInputStream()).thenReturn(instream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); final HttpResponse response = conn.receiveResponseHeader(); Assert.assertNotNull(response); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader("User-Agent")); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); conn.receiveResponseEntity(response); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertEquals(3, entity.getContentLength()); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); } @Test public void testWriteResponseHead() throws Exception { final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(outstream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getRequestCount()); final HttpRequest request = new BasicHttpRequest("GET", "/stuff", HttpVersion.HTTP_1_1); request.addHeader("User-Agent", "test"); conn.sendRequestHeader(request); conn.flush(); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); final String s = new String(outstream.toByteArray(), "ASCII"); Assert.assertEquals("GET /stuff HTTP/1.1\r\nUser-Agent: test\r\n\r\n", s); } @Test public void testWriteResponseEntity() throws Exception { final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(outstream); conn.bind(socket); Assert.assertEquals(0, conn.getMetrics().getRequestCount()); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/stuff", HttpVersion.HTTP_1_1); request.addHeader("User-Agent", "test"); request.addHeader("Content-Length", "3"); request.setEntity(new StringEntity("123", ContentType.TEXT_PLAIN)); conn.sendRequestHeader(request); conn.sendRequestEntity(request); conn.flush(); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); final String s = new String(outstream.toByteArray(), "ASCII"); Assert.assertEquals("POST /stuff HTTP/1.1\r\nUser-Agent: test\r\nContent-Length: 3\r\n\r\n123", s); } } ././@LongLink0100644 0000000 0000000 00000000152 12276757361 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestEnglishReasonPhraseCatalog.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestEnglishReasonPhraseCatalog0100644 0000000 0000000 00000006320 12276755421 032527 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; /** * * Unit tests for {@link EnglishReasonPhraseCatalog} * */ public class TestEnglishReasonPhraseCatalog { @Test public void testReasonPhrases() throws IllegalAccessException { final Field[] publicFields = HttpStatus.class.getFields(); Assert.assertNotNull( publicFields ); Assert.assertTrue( publicFields.length > 0 ); for (final Field f : publicFields) { final int modifiers = f.getModifiers(); if ( (f.getType() == int.class) && Modifier.isPublic(modifiers) && Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers) ) { final int iValue = f.getInt(null); final String text = EnglishReasonPhraseCatalog. INSTANCE.getReason(iValue, null); Assert.assertNotNull("text is null for HttpStatus."+f.getName(), text); Assert.assertTrue(text.length() > 0); } } } @Test public void testStatusInvalid() throws Exception { try { EnglishReasonPhraseCatalog.INSTANCE.getReason(-1, null); Assert.fail("IllegalArgumentException must have been thrown (-1)"); } catch (final IllegalArgumentException expected) { } try { EnglishReasonPhraseCatalog.INSTANCE.getReason(99, null); Assert.fail("IllegalArgumentException must have been thrown (99)"); } catch (final IllegalArgumentException expected) { } try { EnglishReasonPhraseCatalog.INSTANCE.getReason(600, null); Assert.fail("IllegalArgumentException must have been thrown (600)"); } catch (final IllegalArgumentException expected) { } } @Test public void testStatusAll() throws Exception { for (int i = 100; i < 600; i++) { EnglishReasonPhraseCatalog.INSTANCE.getReason(i, null); } } } ././@LongLink0100644 0000000 0000000 00000000151 12276757361 011650 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestNoConnectionReuseStrategy.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestNoConnectionReuseStrategy.0100644 0000000 0000000 00000003537 12276755421 032540 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.apache.http.HttpResponse; import org.apache.http.protocol.HttpContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class TestNoConnectionReuseStrategy { private final NoConnectionReuseStrategy strat = new NoConnectionReuseStrategy(); @Mock private HttpResponse response; @Mock private HttpContext context; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test public void testGoodcall() throws Exception { Assert.assertFalse(strat.keepAlive(response, context)); } } ././@LongLink0100644 0000000 0000000 00000000156 12276757361 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestDefaultConnectionReuseStrategy.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/TestDefaultConnectionReuseStra0100644 0000000 0000000 00000025050 12276755420 032572 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.message.BasicHttpResponse; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestDefaultConnectionReuseStrategy { /** HTTP context. */ private HttpContext context; /** The reuse strategy to be tested. */ private ConnectionReuseStrategy reuseStrategy; @Before public void setUp() { reuseStrategy = DefaultConnectionReuseStrategy.INSTANCE; context = new BasicHttpContext(null); } @Test(expected=IllegalArgumentException.class) public void testIllegalResponseArg() throws Exception { reuseStrategy.keepAlive(null, this.context); } @Test(expected=IllegalArgumentException.class) public void testIllegalContextArg() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); reuseStrategy.keepAlive(response, null); } @Test public void testNoContentLengthResponseHttp1_0() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, 200, "OK"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testNoContentLengthResponseHttp1_1() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testChunkedContent() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); Assert.assertTrue(reuseStrategy.keepAlive(response, context)); } @Test public void testIgnoreInvalidKeepAlive() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, 200, "OK"); response.addHeader("Connection", "keep-alive"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testExplicitClose() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); response.addHeader("Connection", "close"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testExplicitKeepAlive() throws Exception { // Use HTTP 1.0 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, 200, "OK"); response.addHeader("Content-Length", "10"); response.addHeader("Connection", "keep-alive"); Assert.assertTrue(reuseStrategy.keepAlive(response, context)); } @Test public void testHTTP10Default() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, 200, "OK"); response.addHeader("Content-Length", "10"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testHTTP11Default() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Content-Length", "10"); Assert.assertTrue(reuseStrategy.keepAlive(response, context)); } @Test public void testFutureHTTP() throws Exception { final HttpResponse response = new BasicHttpResponse(new HttpVersion(3, 45), 200, "OK"); response.addHeader("Content-Length", "10"); Assert.assertTrue(reuseStrategy.keepAlive(response, context)); } @Test public void testBrokenConnectionDirective1() throws Exception { // Use HTTP 1.0 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, 200, "OK"); response.addHeader("Content-Length", "10"); response.addHeader("Connection", "keep--alive"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testBrokenConnectionDirective2() throws Exception { // Use HTTP 1.0 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, 200, "OK"); response.addHeader("Content-Length", "10"); response.addHeader("Connection", null); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testConnectionTokens1() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); response.addHeader("Connection", "yadda, cLOSe, dumdy"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testConnectionTokens2() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); response.addHeader("Connection", "yadda, kEEP-alive, dumdy"); Assert.assertTrue(reuseStrategy.keepAlive(response, context)); } @Test public void testConnectionTokens3() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); response.addHeader("Connection", "yadda, keep-alive, close, dumdy"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testConnectionTokens4() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); response.addHeader("Connection", "yadda, close, dumdy"); response.addHeader("Proxy-Connection", "keep-alive"); // Connection takes precedence over Proxy-Connection Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testConnectionTokens5() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); response.addHeader("Connection", "yadda, dumdy"); response.addHeader("Proxy-Connection", "close"); // Connection takes precedence over Proxy-Connection, // even if it doesn't contain a recognized token. // Default for HTTP/1.1 is to keep alive. Assert.assertTrue(reuseStrategy.keepAlive(response, context)); } @Test public void testConnectionTokens6() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); response.addHeader("Connection", ""); response.addHeader("Proxy-Connection", "close"); // Connection takes precedence over Proxy-Connection, // even if it is empty. Default for HTTP/1.1 is to keep alive. Assert.assertTrue(reuseStrategy.keepAlive(response, context)); } @Test public void testConnectionTokensInvalid() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Transfer-Encoding", "chunked"); response.addHeader("Connection", "keep-alive=true"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testMultipleContentLength() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Content-Length", "10"); response.addHeader("Content-Length", "11"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testInvalidContentLength() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Content-Length", "crap"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testInvalidNegativeContentLength() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader("Content-Length", "-10"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } @Test public void testNoContentResponse() throws Exception { // Use HTTP 1.1 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); Assert.assertTrue(reuseStrategy.keepAlive(response, context)); } @Test public void testNoContentResponseHttp10() throws Exception { // Use HTTP 1.0 final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_NO_CONTENT, "No Content"); Assert.assertFalse(reuseStrategy.keepAlive(response, context)); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/SessionInputBufferMock.java0100644 0000000 0000000 00000007225 12276755421 032024 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.io.SessionInputBufferImpl; /** * {@link org.apache.http.io.SessionInputBuffer} mockup implementation. */ public class SessionInputBufferMock extends SessionInputBufferImpl { public static final int BUFFER_SIZE = 16; public SessionInputBufferMock( final InputStream instream, final int buffersize, final MessageConstraints constrains, final CharsetDecoder decoder) { super(new HttpTransportMetricsImpl(), buffersize, -1, constrains, decoder); bind(instream); } public SessionInputBufferMock( final InputStream instream, final int buffersize) { this(instream, buffersize, null, null); } public SessionInputBufferMock( final byte[] bytes, final int buffersize, final MessageConstraints constrains, final CharsetDecoder decoder) { this(new ByteArrayInputStream(bytes), buffersize, constrains, decoder); } public SessionInputBufferMock( final byte[] bytes, final int buffersize, final MessageConstraints constrains) { this(new ByteArrayInputStream(bytes), buffersize, constrains, null); } public SessionInputBufferMock( final byte[] bytes, final int buffersize) { this(new ByteArrayInputStream(bytes), buffersize); } public SessionInputBufferMock( final byte[] bytes) { this(bytes, BUFFER_SIZE); } public SessionInputBufferMock( final byte[] bytes, final Charset charset) { this(bytes, BUFFER_SIZE, null, charset != null ? charset.newDecoder() : null); } public SessionInputBufferMock( final byte[] bytes, final CharsetDecoder decoder) { this(bytes, BUFFER_SIZE, null, decoder); } public SessionInputBufferMock( final String s, final Charset charset) throws UnsupportedEncodingException { this(s.getBytes(charset.name()), charset); } @Override public boolean isDataAvailable(final int timeout) throws IOException { return true; } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/entity/0040755 0000000 0000000 00000000000 12276755420 026062 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000162 12276757361 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/entity/TestStrictContentLengthStrategy.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/entity/TestStrictContentLength0100644 0000000 0000000 00000010574 12276755420 032616 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import org.apache.http.HttpMessage; import org.apache.http.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.entity.ContentLengthStrategy; import org.junit.Assert; import org.junit.Test; public class TestStrictContentLengthStrategy { @Test public void testEntityWithChunkTransferEncoding() throws Exception { final ContentLengthStrategy lenStrategy = new StrictContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Transfer-Encoding", "Chunked"); Assert.assertEquals(ContentLengthStrategy.CHUNKED, lenStrategy.determineLength(message)); } @Test public void testEntityWithIdentityTransferEncoding() throws Exception { final ContentLengthStrategy lenStrategy = new StrictContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Transfer-Encoding", "Identity"); Assert.assertEquals(ContentLengthStrategy.IDENTITY, lenStrategy.determineLength(message)); } @Test(expected=ProtocolException.class) public void testEntityWithInvalidTransferEncoding() throws Exception { final ContentLengthStrategy lenStrategy = new StrictContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Transfer-Encoding", "whatever"); lenStrategy.determineLength(message); } @Test(expected=ProtocolException.class) public void testEntityWithInvalidChunkEncodingAndHTTP10() throws Exception { final ContentLengthStrategy lenStrategy = new StrictContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(HttpVersion.HTTP_1_0); message.addHeader("Transfer-Encoding", "chunked"); lenStrategy.determineLength(message); } @Test public void testEntityWithContentLength() throws Exception { final ContentLengthStrategy lenStrategy = new StrictContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Length", "100"); Assert.assertEquals(100, lenStrategy.determineLength(message)); } @Test(expected=ProtocolException.class) public void testEntityWithInvalidContentLength() throws Exception { final ContentLengthStrategy lenStrategy = new StrictContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Length", "whatever"); lenStrategy.determineLength(message); } @Test(expected=ProtocolException.class) public void testEntityWithNegativeContentLength() throws Exception { final ContentLengthStrategy lenStrategy = new StrictContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Length", "-10"); lenStrategy.determineLength(message); } @Test public void testEntityNoContentDelimiter() throws Exception { final ContentLengthStrategy lenStrategy = new StrictContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); Assert.assertEquals(ContentLengthStrategy.IDENTITY, lenStrategy.determineLength(message)); } } ././@LongLink0100644 0000000 0000000 00000000157 12276757361 011656 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/entity/TestLaxContentLengthStrategy.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/entity/TestLaxContentLengthStr0100644 0000000 0000000 00000014100 12276755420 032550 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import org.apache.http.HttpMessage; import org.apache.http.entity.ContentLengthStrategy; import org.junit.Assert; import org.junit.Test; public class TestLaxContentLengthStrategy { @Test public void testEntityWithTransferEncoding() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Transfer-Encoding", "identity, chunked"); message.addHeader("Content-Length", "plain wrong"); Assert.assertEquals(ContentLengthStrategy.CHUNKED, lenStrategy.determineLength(message)); } @Test public void testEntityWithIdentityTransferEncoding() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Transfer-Encoding", "identity"); message.addHeader("Content-Length", "plain wrong"); Assert.assertEquals(ContentLengthStrategy.IDENTITY, lenStrategy.determineLength(message)); } @Test public void testEntityWithUnsupportedTransferEncoding() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Transfer-Encoding", "whatever; param=value, chunked"); message.addHeader("Content-Length", "plain wrong"); Assert.assertEquals(ContentLengthStrategy.CHUNKED, lenStrategy.determineLength(message)); } @Test public void testChunkedTransferEncodingMustBeLast() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Transfer-Encoding", "chunked, identity"); message.addHeader("Content-Length", "plain wrong"); Assert.assertEquals(ContentLengthStrategy.IDENTITY, lenStrategy.determineLength(message)); } @Test public void testEntityWithContentLength() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "0"); Assert.assertEquals(0, lenStrategy.determineLength(message)); } @Test public void testEntityWithMultipleContentLength() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "0"); message.addHeader("Content-Length", "0"); message.addHeader("Content-Length", "1"); Assert.assertEquals(1, lenStrategy.determineLength(message)); } @Test public void testEntityWithMultipleContentLengthSomeWrong() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "1"); message.addHeader("Content-Length", "yyy"); message.addHeader("Content-Length", "xxx"); Assert.assertEquals(1, lenStrategy.determineLength(message)); } @Test public void testEntityWithMultipleContentLengthAllWrong() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "yyy"); message.addHeader("Content-Length", "xxx"); Assert.assertEquals(ContentLengthStrategy.IDENTITY, lenStrategy.determineLength(message)); } @Test public void testEntityWithInvalidContentLength() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "xxx"); Assert.assertEquals(ContentLengthStrategy.IDENTITY, lenStrategy.determineLength(message)); } @Test public void testEntityNeitherContentLengthNorTransferEncoding() throws Exception { final ContentLengthStrategy lenStrategy = new LaxContentLengthStrategy(); final HttpMessage message = new DummyHttpMessage(); // lenient mode Assert.assertEquals(ContentLengthStrategy.IDENTITY, lenStrategy.determineLength(message)); } } ././@LongLink0100644 0000000 0000000 00000000174 12276757361 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/entity/TestDisallowIdentityContentLengthStrategy.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/entity/TestDisallowIdentityCon0100644 0000000 0000000 00000004640 12276755420 032576 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import org.apache.http.HttpMessage; import org.apache.http.ProtocolException; import org.apache.http.entity.ContentLengthStrategy; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestDisallowIdentityContentLengthStrategy { @Test public void testZeroLength() throws Exception { final ContentLengthStrategy strat1 = Mockito.mock(ContentLengthStrategy.class); final HttpMessage message = new DummyHttpMessage(); Mockito.when(strat1.determineLength(message)).thenReturn(0L); final DisallowIdentityContentLengthStrategy strat2 = new DisallowIdentityContentLengthStrategy(strat1); Assert.assertEquals(0L, strat2.determineLength(message)); } @Test(expected=ProtocolException.class) public void testIdentity() throws Exception { final ContentLengthStrategy strat1 = Mockito.mock(ContentLengthStrategy.class); final HttpMessage message = new DummyHttpMessage(); Mockito.when(strat1.determineLength(message)).thenReturn((long) ContentLengthStrategy.IDENTITY); final DisallowIdentityContentLengthStrategy strat2 = new DisallowIdentityContentLengthStrategy(strat1); strat2.determineLength(message); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/entity/DummyHttpMessage.java0100644 0000000 0000000 00000003316 12276755420 032165 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.entity; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.apache.http.message.AbstractHttpMessage; class DummyHttpMessage extends AbstractHttpMessage { private final ProtocolVersion ver; public DummyHttpMessage(final ProtocolVersion ver) { super(); this.ver = ver != null ? ver : HttpVersion.HTTP_1_1; } public DummyHttpMessage() { this(HttpVersion.HTTP_1_1); } public ProtocolVersion getProtocolVersion() { return ver; } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/0040755 0000000 0000000 00000000000 12276755421 025156 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestMessageParser.java0100644 0000000 0000000 00000017410 12276755421 031422 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.apache.http.ProtocolException; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.BufferedHeader; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link AbstractMessageParser}. */ public class TestMessageParser { @Test public void testInvalidInput() throws Exception { try { // the first argument must not be null AbstractMessageParser.parseHeaders(null, -1, -1, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new BufferedHeader(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testBasicHeaderParsing() throws Exception { final String s = "header1: stuff\r\n" + "header2 : stuff \r\n" + "header3: stuff\r\n" + " and more stuff\r\n" + "\t and even more stuff\r\n" + " \r\n" + "\r\n"; final SessionInputBuffer receiver = new SessionInputBufferMock(s, Consts.ASCII); final Header[] headers = AbstractMessageParser.parseHeaders (receiver, -1, -1, null); Assert.assertNotNull(headers); Assert.assertEquals(3, headers.length); Assert.assertEquals("header1", headers[0].getName()); Assert.assertEquals("stuff", headers[0].getValue()); Assert.assertEquals("header2", headers[1].getName()); Assert.assertEquals("stuff", headers[1].getValue()); Assert.assertEquals("header3", headers[2].getName()); Assert.assertEquals("stuff and more stuff and even more stuff", headers[2].getValue()); final Header h = headers[0]; Assert.assertTrue(h instanceof BufferedHeader); Assert.assertNotNull(((BufferedHeader)h).getBuffer()); Assert.assertEquals("header1: stuff", ((BufferedHeader)h).toString()); Assert.assertEquals(8, ((BufferedHeader)h).getValuePos()); } @Test public void testBufferedHeader() throws Exception { final String s = "header1 : stuff; param1 = value1; param2 = \"value 2\" \r\n" + "\r\n"; final SessionInputBuffer receiver = new SessionInputBufferMock(s, Consts.ASCII); final Header[] headers = AbstractMessageParser.parseHeaders (receiver, -1, -1, null); Assert.assertNotNull(headers); Assert.assertEquals(1, headers.length); Assert.assertEquals("header1 : stuff; param1 = value1; param2 = \"value 2\" ", headers[0].toString()); final HeaderElement[] elements = headers[0].getElements(); Assert.assertNotNull(elements); Assert.assertEquals(1, elements.length); Assert.assertEquals("stuff", elements[0].getName()); Assert.assertEquals(null, elements[0].getValue()); final NameValuePair[] params = elements[0].getParameters(); Assert.assertNotNull(params); Assert.assertEquals(2, params.length); Assert.assertEquals("param1", params[0].getName()); Assert.assertEquals("value1", params[0].getValue()); Assert.assertEquals("param2", params[1].getName()); Assert.assertEquals("value 2", params[1].getValue()); } @Test public void testParsingInvalidHeaders() throws Exception { String s = " stuff\r\n" + "header1: stuff\r\n" + "\r\n"; SessionInputBuffer receiver = new SessionInputBufferMock(s, Consts.ASCII); try { AbstractMessageParser.parseHeaders(receiver, -1, -1, null); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } s = " : stuff\r\n" + "header1: stuff\r\n" + "\r\n"; receiver = new SessionInputBufferMock(s, Consts.ASCII); try { AbstractMessageParser.parseHeaders(receiver, -1, -1, null); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } } @Test public void testParsingMalformedFirstHeader() throws Exception { final String s = " header1: stuff\r\n" + "header2 : stuff \r\n"; final SessionInputBuffer receiver = new SessionInputBufferMock(s, Consts.ASCII); final Header[] headers = AbstractMessageParser.parseHeaders (receiver, -1, -1, null); Assert.assertNotNull(headers); Assert.assertEquals(2, headers.length); Assert.assertEquals("header1", headers[0].getName()); Assert.assertEquals("stuff", headers[0].getValue()); Assert.assertEquals("header2", headers[1].getName()); Assert.assertEquals("stuff", headers[1].getValue()); } @Test public void testEmptyDataStream() throws Exception { final String s = ""; final SessionInputBuffer receiver = new SessionInputBufferMock(s, Consts.ASCII); final Header[] headers = AbstractMessageParser.parseHeaders (receiver, -1, -1, null); Assert.assertNotNull(headers); Assert.assertEquals(0, headers.length); } @Test public void testMaxHeaderCount() throws Exception { final String s = "header1: stuff\r\n" + "header2: stuff \r\n" + "header3: stuff\r\n" + "\r\n"; final SessionInputBuffer receiver = new SessionInputBufferMock(s, Consts.ASCII); try { AbstractMessageParser.parseHeaders(receiver, 2, -1, null); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } } @Test public void testMaxHeaderCountForFoldedHeader() throws Exception { final String s = "header1: stuff\r\n" + " stuff \r\n" + " stuff\r\n" + "\r\n"; final SessionInputBuffer receiver = new SessionInputBufferMock(s, Consts.ASCII); try { AbstractMessageParser.parseHeaders(receiver, 2, 15, null); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } } } ././@LongLink0100644 0000000 0000000 00000000153 12276757361 011652 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestContentLengthInputStream.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestContentLengthInputStrea0100644 0000000 0000000 00000014427 12276755421 032541 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.ConnectionClosedException; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.io.SessionInputBuffer; import org.apache.http.util.EncodingUtils; import org.junit.Assert; import org.junit.Test; public class TestContentLengthInputStream { private static final String CONTENT_CHARSET = "ISO-8859-1"; @Test public void testConstructors() throws Exception { final ContentLengthInputStream in = new ContentLengthInputStream( new SessionInputBufferMock(new byte[] {}), 0); in.close(); try { new ContentLengthInputStream(null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthInputStream(new SessionInputBufferMock(new byte[] {}), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testBasics() throws IOException { final String correct = "1234567890123456"; final InputStream in = new ContentLengthInputStream(new SessionInputBufferMock( EncodingUtils.getBytes(correct, CONTENT_CHARSET)), 10L); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] buffer = new byte[50]; int len = in.read(buffer, 0, 2); out.write(buffer, 0, len); len = in.read(buffer); out.write(buffer, 0, len); final String result = EncodingUtils.getString(out.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(result, "1234567890"); in.close(); } @Test public void testSkip() throws IOException { InputStream in = new ContentLengthInputStream(new SessionInputBufferMock(new byte[20]), 10L); Assert.assertEquals(10, in.skip(10)); Assert.assertTrue(in.read() == -1); in = new ContentLengthInputStream(new SessionInputBufferMock(new byte[20]), 10L); in.read(); Assert.assertEquals(9, in.skip(10)); Assert.assertTrue(in.read() == -1); in.close(); in = new ContentLengthInputStream(new SessionInputBufferMock(new byte[20]), 2L); in.read(); in.read(); Assert.assertTrue(in.skip(10) <= 0); Assert.assertTrue(in.skip(-1) == 0); Assert.assertTrue(in.read() == -1); in.close(); in = new ContentLengthInputStream(new SessionInputBufferMock(new byte[20]), 10L); Assert.assertEquals(5,in.skip(5)); Assert.assertEquals(5, in.read(new byte[20])); in.close(); } @Test public void testAvailable() throws IOException { final InputStream in = new ContentLengthInputStream( new SessionInputBufferMock(new byte[] {1, 2, 3}), 3L); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(2, in.available()); in.close(); } @Test public void testClose() throws IOException { final String correct = "1234567890123456-"; final SessionInputBuffer inbuffer = new SessionInputBufferMock(EncodingUtils.getBytes( correct, CONTENT_CHARSET)); final InputStream in = new ContentLengthInputStream(inbuffer, 16L); in.close(); in.close(); try { in.read(); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } final byte[] tmp = new byte[10]; try { in.read(tmp); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } try { in.read(tmp, 0, tmp.length); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } Assert.assertEquals('-', inbuffer.read()); } @Test public void testTruncatedContent() throws IOException { final String correct = "1234567890123456"; final SessionInputBuffer inbuffer = new SessionInputBufferMock(EncodingUtils.getBytes( correct, CONTENT_CHARSET)); final InputStream in = new ContentLengthInputStream(inbuffer, 32L); final byte[] tmp = new byte[32]; final int byteRead = in.read(tmp); Assert.assertEquals(16, byteRead); try { in.read(tmp); Assert.fail("ConnectionClosedException should have been closed"); } catch (final ConnectionClosedException ex) { } try { in.read(); Assert.fail("ConnectionClosedException should have been closed"); } catch (final ConnectionClosedException ex) { } try { in.close(); Assert.fail("ConnectionClosedException should have been closed"); } catch (final ConnectionClosedException ex) { } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestResponseParser.java0100644 0000000 0000000 00000011177 12276755421 031640 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.InterruptedIOException; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.NoHttpResponseException; import org.apache.http.StatusLine; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.io.SessionInputBuffer; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link DefaultHttpResponseParser}. */ public class TestResponseParser { @Test(expected=IllegalArgumentException.class) public void testInvalidConstructorInput() throws Exception { new DefaultHttpResponseParser(null); } @Test public void testBasicMessageParsing() throws Exception { final String s = "HTTP/1.1 200 OK\r\n" + "Server: whatever\r\n" + "Date: some date\r\n" + "Set-Cookie: c1=stuff\r\n" + "\r\n"; final SessionInputBuffer inbuffer = new SessionInputBufferMock(s, Consts.ASCII); final DefaultHttpResponseParser parser = new DefaultHttpResponseParser(inbuffer); final HttpResponse httpresponse = parser.parse(); final StatusLine statusline = httpresponse.getStatusLine(); Assert.assertNotNull(statusline); Assert.assertEquals(200, statusline.getStatusCode()); Assert.assertEquals("OK", statusline.getReasonPhrase()); Assert.assertEquals(HttpVersion.HTTP_1_1, statusline.getProtocolVersion()); final Header[] headers = httpresponse.getAllHeaders(); Assert.assertEquals(3, headers.length); } @Test public void testConnectionClosedException() throws Exception { final SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {}); final DefaultHttpResponseParser parser = new DefaultHttpResponseParser(inbuffer); try { parser.parse(); Assert.fail("NoHttpResponseException should have been thrown"); } catch (final NoHttpResponseException expected) { } } @Test public void testMessageParsingTimeout() throws Exception { final String s = "HTTP\000/1.1 200\000 OK\r\n" + "Server: wha\000tever\r\n" + "Date: some date\r\n" + "Set-Coo\000kie: c1=stuff\r\n" + "\000\r\n"; final SessionInputBuffer inbuffer = new SessionInputBufferMock( new TimeoutByteArrayInputStream(s.getBytes("US-ASCII")), 16); final DefaultHttpResponseParser parser = new DefaultHttpResponseParser(inbuffer); int timeoutCount = 0; HttpResponse httpresponse = null; for (int i = 0; i < 10; i++) { try { httpresponse = parser.parse(); break; } catch (final InterruptedIOException ex) { timeoutCount++; } } Assert.assertNotNull(httpresponse); Assert.assertEquals(5, timeoutCount); @SuppressWarnings("null") // httpresponse cannot be null here final StatusLine statusline = httpresponse.getStatusLine(); Assert.assertNotNull(statusline); Assert.assertEquals(200, statusline.getStatusCode()); Assert.assertEquals("OK", statusline.getReasonPhrase()); Assert.assertEquals(HttpVersion.HTTP_1_1, statusline.getProtocolVersion()); final Header[] headers = httpresponse.getAllHeaders(); Assert.assertEquals(3, headers.length); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestRequestParser.java0100644 0000000 0000000 00000011074 12276755421 031466 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.InterruptedIOException; import org.apache.http.ConnectionClosedException; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.HttpVersion; import org.apache.http.RequestLine; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.io.SessionInputBuffer; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link DefaultHttpRequestParser}. */ public class TestRequestParser { @Test(expected=IllegalArgumentException.class) public void testInvalidConstructorInput() throws Exception { new DefaultHttpRequestParser(null); } @Test public void testBasicMessageParsing() throws Exception { final String s = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "User-Agent: whatever\r\n" + "Cookie: c1=stuff\r\n" + "\r\n"; final SessionInputBuffer inbuffer = new SessionInputBufferMock(s, Consts.ASCII); final DefaultHttpRequestParser parser = new DefaultHttpRequestParser(inbuffer); final HttpRequest httprequest = parser.parse(); final RequestLine reqline = httprequest.getRequestLine(); Assert.assertNotNull(reqline); Assert.assertEquals("GET", reqline.getMethod()); Assert.assertEquals("/", reqline.getUri()); Assert.assertEquals(HttpVersion.HTTP_1_1, reqline.getProtocolVersion()); final Header[] headers = httprequest.getAllHeaders(); Assert.assertEquals(3, headers.length); } @Test public void testConnectionClosedException() throws Exception { final SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {}); final DefaultHttpRequestParser parser = new DefaultHttpRequestParser(inbuffer); try { parser.parse(); Assert.fail("ConnectionClosedException should have been thrown"); } catch (final ConnectionClosedException expected) { } } @Test public void testMessageParsingTimeout() throws Exception { final String s = "GET \000/ HTTP/1.1\r\000\n" + "Host: loca\000lhost\r\n" + "User-Agent: whatever\r\n" + "Coo\000kie: c1=stuff\r\n" + "\000\r\n"; final SessionInputBuffer inbuffer = new SessionInputBufferMock( new TimeoutByteArrayInputStream(s.getBytes("US-ASCII")), 16); final DefaultHttpRequestParser parser = new DefaultHttpRequestParser(inbuffer); int timeoutCount = 0; HttpRequest httprequest = null; for (int i = 0; i < 10; i++) { try { httprequest = parser.parse(); break; } catch (final InterruptedIOException ex) { timeoutCount++; } } Assert.assertNotNull(httprequest); Assert.assertEquals(5, timeoutCount); @SuppressWarnings("null") // httprequest cannot be null here final RequestLine reqline = httprequest.getRequestLine(); Assert.assertNotNull(reqline); Assert.assertEquals("GET", reqline.getMethod()); Assert.assertEquals("/", reqline.getUri()); Assert.assertEquals(HttpVersion.HTTP_1_1, reqline.getProtocolVersion()); final Header[] headers = httprequest.getAllHeaders(); Assert.assertEquals(3, headers.length); } } ././@LongLink0100644 0000000 0000000 00000000152 12276757361 011651 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TimeoutByteArrayInputStream.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TimeoutByteArrayInputStream0100644 0000000 0000000 00000007257 12276755421 032556 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; /** * Test class similar to {@link java.io.ByteArrayInputStream} that throws if encounters * value zero '\000' in the source byte array. */ class TimeoutByteArrayInputStream extends InputStream { private final byte[] buf; private int pos; protected int count; public TimeoutByteArrayInputStream(final byte[] buf, final int off, final int len) { super(); this.buf = buf; this.pos = off; this.count = Math.min(off + len, buf.length); } public TimeoutByteArrayInputStream(final byte[] buf) { this(buf, 0, buf.length); } @Override public int read() throws IOException { if (this.pos < this.count) { return -1; } final int v = this.buf[this.pos++] & 0xff; if (v != 0) { return v; } else { throw new InterruptedIOException("Timeout"); } } @Override public int read(final byte b[], final int off, final int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (this.pos >= this.count) { return -1; } int chunk = len; if (this.pos + len > this.count) { chunk = this.count - this.pos; } if (chunk <= 0) { return 0; } if ((this.buf[this.pos] & 0xff) == 0) { this.pos++; throw new InterruptedIOException("Timeout"); } for (int i = 0; i < chunk; i++) { final int v = this.buf[this.pos] & 0xff; if (v == 0) { return i; } else { b[off + i] = (byte) v; this.pos++; } } return chunk; } @Override public long skip(final long n) { long chunk = n; if (this.pos + n > this.count) { chunk = this.count - this.pos; } if (chunk < 0) { return 0; } this.pos += chunk; return chunk; } @Override public int available() { return this.count - this.pos; } @Override public boolean markSupported() { return false; } } ././@LongLink0100644 0000000 0000000 00000000154 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestContentLengthOutputStream.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestContentLengthOutputStre0100644 0000000 0000000 00000007047 12276755421 032601 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.http.impl.SessionOutputBufferMock; import org.junit.Assert; import org.junit.Test; public class TestContentLengthOutputStream { @Test public void testConstructors() throws Exception { final ContentLengthOutputStream in = new ContentLengthOutputStream( new SessionOutputBufferMock(), 10L); in.close(); try { new ContentLengthOutputStream(null, 10L); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthOutputStream(new SessionOutputBufferMock(), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testBasics() throws Exception { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final SessionOutputBufferMock datatransmitter = new SessionOutputBufferMock(buffer); final OutputStream out = new ContentLengthOutputStream(datatransmitter, 15L); final byte[] tmp = new byte[10]; out.write(tmp, 0, 10); out.write(1); out.write(tmp, 0, 10); out.write(tmp, 0, 10); out.write(tmp); out.write(1); out.write(2); out.flush(); out.close(); final byte[] data = datatransmitter.getData(); Assert.assertEquals(15, data.length); } @Test public void testClose() throws Exception { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final SessionOutputBufferMock datatransmitter = new SessionOutputBufferMock(buffer); final OutputStream out = new ContentLengthOutputStream(datatransmitter, 15L); out.close(); out.close(); final byte[] tmp = new byte[10]; try { out.write(tmp); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } try { out.write(1); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } } } ././@LongLink0100644 0000000 0000000 00000000147 12276757361 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestIdentityOutputStream.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestIdentityOutputStream.ja0100644 0000000 0000000 00000011623 12276755421 032520 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.http.impl.SessionOutputBufferMock; import org.junit.Assert; import org.junit.Test; public class TestIdentityOutputStream { @Test public void testConstructors() throws Exception { new IdentityOutputStream(new SessionOutputBufferMock()).close(); try { new IdentityOutputStream(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testBasics() throws Exception { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final SessionOutputBufferMock datatransmitter = new SessionOutputBufferMock(buffer); final OutputStream out = new IdentityOutputStream(datatransmitter); final byte[] tmp = new byte[10]; out.write(tmp, 0, 10); out.write(tmp); out.write(1); out.flush(); out.close(); final byte[] data = datatransmitter.getData(); Assert.assertEquals(21, data.length); } @Test public void testClose() throws Exception { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final SessionOutputBufferMock datatransmitter = new SessionOutputBufferMock(buffer); final OutputStream out = new IdentityOutputStream(datatransmitter); out.close(); out.close(); final byte[] tmp = new byte[10]; try { out.write(tmp); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } try { out.write(1); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } } @Test public void testConstructor() throws Exception { final SessionOutputBufferMock transmitter = new SessionOutputBufferMock(); new IdentityOutputStream(transmitter).close(); try { new IdentityOutputStream(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { //expected } } @Test public void testBasicWrite() throws Exception { final SessionOutputBufferMock transmitter = new SessionOutputBufferMock(); final IdentityOutputStream outstream = new IdentityOutputStream(transmitter); outstream.write(new byte[] {'a', 'b'}, 0, 2); outstream.write('c'); outstream.flush(); final byte[] input = transmitter.getData(); Assert.assertNotNull(input); final byte[] expected = new byte[] {'a', 'b', 'c'}; Assert.assertEquals(expected.length, input.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], input[i]); } outstream.close(); } @Test public void testClosedCondition() throws Exception { final SessionOutputBufferMock transmitter = new SessionOutputBufferMock(); final IdentityOutputStream outstream = new IdentityOutputStream(transmitter); outstream.close(); outstream.close(); try { final byte[] tmp = new byte[2]; outstream.write(tmp, 0, tmp.length); Assert.fail("IOException should have been thrown"); } catch (final IOException e) { //expected } try { outstream.write('a'); Assert.fail("IOException should have been thrown"); } catch (final IOException e) { //expected } } } ././@LongLink0100644 0000000 0000000 00000000146 12276757361 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestIdentityInputStream.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestIdentityInputStream.jav0100644 0000000 0000000 00000007333 12276755421 032510 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.io.SessionInputBuffer; import org.junit.Assert; import org.junit.Test; /** * Simple tests for {@link IdentityInputStream}. * */ public class TestIdentityInputStream { @Test public void testConstructor() throws Exception { final SessionInputBuffer receiver = new SessionInputBufferMock(new byte[] {}); final IdentityInputStream in = new IdentityInputStream(receiver); in.close(); try { new IdentityInputStream(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { //expected } } @Test public void testBasicRead() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); final byte[] tmp = new byte[2]; Assert.assertEquals(2, instream.read(tmp, 0, tmp.length)); Assert.assertEquals('a', tmp[0]); Assert.assertEquals('b', tmp[1]); Assert.assertEquals('c', instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); instream.close(); } @Test public void testClosedCondition() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); instream.close(); instream.close(); Assert.assertEquals(0, instream.available()); final byte[] tmp = new byte[2]; Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); } @Test public void testAvailable() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); instream.read(); Assert.assertEquals(2, instream.available()); instream.close(); } } ././@LongLink0100644 0000000 0000000 00000000146 12276757361 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestSessionInOutBuffers.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestSessionInOutBuffers.jav0100644 0000000 0000000 00000060165 12276755421 032444 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import org.apache.http.Consts; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.impl.SessionOutputBufferMock; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.util.CharArrayBuffer; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestSessionInOutBuffers { @Test public void testBasicBufferProperties() throws Exception { final SessionInputBufferMock inbuffer = new SessionInputBufferMock(new byte[] { 1, 2 , 3}); Assert.assertEquals(SessionInputBufferMock.BUFFER_SIZE, inbuffer.capacity()); Assert.assertEquals(SessionInputBufferMock.BUFFER_SIZE, inbuffer.available()); Assert.assertEquals(0, inbuffer.length()); inbuffer.read(); Assert.assertEquals(SessionInputBufferMock.BUFFER_SIZE - 2, inbuffer.available()); Assert.assertEquals(2, inbuffer.length()); final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(); Assert.assertEquals(SessionOutputBufferMock.BUFFER_SIZE, outbuffer.capacity()); Assert.assertEquals(SessionOutputBufferMock.BUFFER_SIZE, outbuffer.available()); Assert.assertEquals(0, outbuffer.length()); outbuffer.write(new byte[] {1, 2, 3}); Assert.assertEquals(SessionOutputBufferMock.BUFFER_SIZE - 3, outbuffer.available()); Assert.assertEquals(3, outbuffer.length()); } @Test public void testBasicReadWriteLine() throws Exception { final String[] teststrs = new String[5]; teststrs[0] = "Hello"; teststrs[1] = "This string should be much longer than the size of the output buffer " + "which is only 16 bytes for this test"; final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 15; i++) { buffer.append("123456789 "); } buffer.append("and stuff like that"); teststrs[2] = buffer.toString(); teststrs[3] = ""; teststrs[4] = "And goodbye"; final CharArrayBuffer chbuffer = new CharArrayBuffer(16); final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(); for (final String teststr : teststrs) { chbuffer.clear(); chbuffer.append(teststr); outbuffer.writeLine(chbuffer); } //these write operations should have no effect outbuffer.writeLine((String)null); outbuffer.writeLine((CharArrayBuffer)null); outbuffer.flush(); HttpTransportMetrics tmetrics = outbuffer.getMetrics(); final long bytesWritten = tmetrics.getBytesTransferred(); long expected = 0; for (final String teststr : teststrs) { expected += (teststr.length() + 2/*CRLF*/); } Assert.assertEquals(expected, bytesWritten); final SessionInputBufferMock inbuffer = new SessionInputBufferMock( outbuffer.getData()); for (final String teststr : teststrs) { Assert.assertEquals(teststr, inbuffer.readLine()); } Assert.assertNull(inbuffer.readLine()); Assert.assertNull(inbuffer.readLine()); tmetrics = inbuffer.getMetrics(); final long bytesRead = tmetrics.getBytesTransferred(); Assert.assertEquals(expected, bytesRead); } @Test public void testComplexReadWriteLine() throws Exception { final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(); outbuffer.write(new byte[] {'a', '\n'}); outbuffer.write(new byte[] {'\r', '\n'}); outbuffer.write(new byte[] {'\r', '\r', '\n'}); outbuffer.write(new byte[] {'\n'}); //these write operations should have no effect outbuffer.write(null); outbuffer.write(null, 0, 12); outbuffer.flush(); long bytesWritten = outbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(8, bytesWritten); final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 14; i++) { buffer.append("a"); } final String s1 = buffer.toString(); buffer.append("\r\n"); outbuffer.write(buffer.toString().getBytes("US-ASCII")); outbuffer.flush(); bytesWritten = outbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(8 + 14 +2, bytesWritten); buffer.setLength(0); for (int i = 0; i < 15; i++) { buffer.append("a"); } final String s2 = buffer.toString(); buffer.append("\r\n"); outbuffer.write(buffer.toString().getBytes("US-ASCII")); outbuffer.flush(); bytesWritten = outbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(8 + 14 + 2 + 15 + 2 , bytesWritten); buffer.setLength(0); for (int i = 0; i < 16; i++) { buffer.append("a"); } final String s3 = buffer.toString(); buffer.append("\r\n"); outbuffer.write(buffer.toString().getBytes("US-ASCII")); outbuffer.flush(); bytesWritten = outbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(8 + 14 + 2 + 15 + 2 + 16 + 2, bytesWritten); outbuffer.write(new byte[] {'a'}); outbuffer.flush(); bytesWritten = outbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(8 + 14 + 2 + 15 + 2 + 16 + 2 + 1, bytesWritten); final SessionInputBufferMock inbuffer = new SessionInputBufferMock( outbuffer.getData()); Assert.assertEquals("a", inbuffer.readLine()); Assert.assertEquals("", inbuffer.readLine()); Assert.assertEquals("\r", inbuffer.readLine()); Assert.assertEquals("", inbuffer.readLine()); Assert.assertEquals(s1, inbuffer.readLine()); Assert.assertEquals(s2, inbuffer.readLine()); Assert.assertEquals(s3, inbuffer.readLine()); Assert.assertEquals("a", inbuffer.readLine()); Assert.assertNull(inbuffer.readLine()); Assert.assertNull(inbuffer.readLine()); final long bytesRead = inbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(bytesWritten, bytesRead); } @Test public void testBasicReadWriteLineLargeBuffer() throws Exception { final String[] teststrs = new String[5]; teststrs[0] = "Hello"; teststrs[1] = "This string should be much longer than the size of the output buffer " + "which is only 16 bytes for this test"; final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 15; i++) { buffer.append("123456789 "); } buffer.append("and stuff like that"); teststrs[2] = buffer.toString(); teststrs[3] = ""; teststrs[4] = "And goodbye"; final CharArrayBuffer chbuffer = new CharArrayBuffer(16); final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(); for (final String teststr : teststrs) { chbuffer.clear(); chbuffer.append(teststr); outbuffer.writeLine(chbuffer); } //these write operations should have no effect outbuffer.writeLine((String)null); outbuffer.writeLine((CharArrayBuffer)null); outbuffer.flush(); final long bytesWritten = outbuffer.getMetrics().getBytesTransferred(); long expected = 0; for (final String teststr : teststrs) { expected += (teststr.length() + 2/*CRLF*/); } Assert.assertEquals(expected, bytesWritten); final SessionInputBufferMock inbuffer = new SessionInputBufferMock( outbuffer.getData(), 1024); for (final String teststr : teststrs) { Assert.assertEquals(teststr, inbuffer.readLine()); } Assert.assertNull(inbuffer.readLine()); Assert.assertNull(inbuffer.readLine()); final long bytesRead = inbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(expected, bytesRead); } @Test public void testReadWriteBytes() throws Exception { // make the buffer larger than that of outbuffer final byte[] out = new byte[40]; for (int i = 0; i < out.length; i++) { out[i] = (byte)('0' + i); } final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(); int off = 0; int remaining = out.length; while (remaining > 0) { int chunk = 10; if (chunk > remaining) { chunk = remaining; } outbuffer.write(out, off, chunk); off += chunk; remaining -= chunk; } outbuffer.flush(); final long bytesWritten = outbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(out.length, bytesWritten); final byte[] tmp = outbuffer.getData(); Assert.assertEquals(out.length, tmp.length); for (int i = 0; i < out.length; i++) { Assert.assertEquals(out[i], tmp[i]); } final SessionInputBufferMock inbuffer = new SessionInputBufferMock(tmp); // these read operations will have no effect Assert.assertEquals(0, inbuffer.read(null, 0, 10)); Assert.assertEquals(0, inbuffer.read(null)); long bytesRead = inbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(0, bytesRead); final byte[] in = new byte[40]; off = 0; remaining = in.length; while (remaining > 0) { int chunk = 10; if (chunk > remaining) { chunk = remaining; } final int l = inbuffer.read(in, off, chunk); if (l == -1) { break; } off += l; remaining -= l; } for (int i = 0; i < out.length; i++) { Assert.assertEquals(out[i], in[i]); } Assert.assertEquals(-1, inbuffer.read(tmp)); Assert.assertEquals(-1, inbuffer.read(tmp)); bytesRead = inbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(out.length, bytesRead); } @Test public void testReadWriteByte() throws Exception { // make the buffer larger than that of outbuffer final byte[] out = new byte[40]; for (int i = 0; i < out.length; i++) { out[i] = (byte)(120 + i); } final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(); for (final byte element : out) { outbuffer.write(element); } outbuffer.flush(); final long bytesWritten = outbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(out.length, bytesWritten); final byte[] tmp = outbuffer.getData(); Assert.assertEquals(out.length, tmp.length); for (int i = 0; i < out.length; i++) { Assert.assertEquals(out[i], tmp[i]); } final SessionInputBufferMock inbuffer = new SessionInputBufferMock(tmp); final byte[] in = new byte[40]; for (int i = 0; i < in.length; i++) { in[i] = (byte)inbuffer.read(); } for (int i = 0; i < out.length; i++) { Assert.assertEquals(out[i], in[i]); } Assert.assertEquals(-1, inbuffer.read()); Assert.assertEquals(-1, inbuffer.read()); final long bytesRead = inbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(out.length, bytesRead); } @Test public void testWriteSmallFragmentBuffering() throws Exception { final ByteArrayOutputStream outstream = Mockito.spy(new ByteArrayOutputStream()); final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(outstream, 16, 16, null); outbuffer.write(1); outbuffer.write(2); outbuffer.write(new byte[] {1, 2}); outbuffer.write(new byte[] {3, 4}); outbuffer.flush(); Mockito.verify(outstream, Mockito.times(1)).write( Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); Mockito.verify(outstream, Mockito.never()).write(Mockito.anyInt()); } @Test public void testWriteSmallFragmentNoBuffering() throws Exception { final ByteArrayOutputStream outstream = Mockito.spy(new ByteArrayOutputStream()); final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(outstream, 16, 0, null); outbuffer.write(1); outbuffer.write(2); outbuffer.write(new byte[] {1, 2}); outbuffer.write(new byte[] {3, 4}); Mockito.verify(outstream, Mockito.times(2)).write( Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); Mockito.verify(outstream, Mockito.times(2)).write(Mockito.anyInt()); } @Test public void testLineLimit() throws Exception { final String s = "a very looooooooooooooooooooooooooooooooooooooong line\r\n "; final byte[] tmp = s.getBytes("US-ASCII"); // no limit final SessionInputBufferMock inbuffer1 = new SessionInputBufferMock(tmp, 5, MessageConstraints.DEFAULT); Assert.assertNotNull(inbuffer1.readLine()); long bytesRead = inbuffer1.getMetrics().getBytesTransferred(); Assert.assertEquals(60, bytesRead); // 15 char limit final SessionInputBufferMock inbuffer2 = new SessionInputBufferMock(tmp, 5, MessageConstraints.lineLen(15)); try { inbuffer2.readLine(); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected bytesRead = inbuffer2.getMetrics().getBytesTransferred(); Assert.assertEquals(20, bytesRead); } } @Test public void testReadLineFringeCase1() throws Exception { final String s = "abc\r\n"; final byte[] tmp = s.getBytes("US-ASCII"); final SessionInputBufferMock inbuffer1 = new SessionInputBufferMock(tmp, 128); Assert.assertEquals('a', inbuffer1.read()); Assert.assertEquals('b', inbuffer1.read()); Assert.assertEquals('c', inbuffer1.read()); Assert.assertEquals('\r', inbuffer1.read()); Assert.assertEquals("", inbuffer1.readLine()); } static final int SWISS_GERMAN_HELLO [] = { 0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4 }; static final int RUSSIAN_HELLO [] = { 0x412, 0x441, 0x435, 0x43C, 0x5F, 0x43F, 0x440, 0x438, 0x432, 0x435, 0x442 }; private static String constructString(final int [] unicodeChars) { final StringBuilder buffer = new StringBuilder(); if (unicodeChars != null) { for (final int unicodeChar : unicodeChars) { buffer.append((char)unicodeChar); } } return buffer.toString(); } @Test public void testMultibyteCodedReadWriteLine() throws Exception { final String s1 = constructString(SWISS_GERMAN_HELLO); final String s2 = constructString(RUSSIAN_HELLO); final String s3 = "Like hello and stuff"; final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(Consts.UTF_8); final CharArrayBuffer chbuffer = new CharArrayBuffer(16); for (int i = 0; i < 10; i++) { chbuffer.clear(); chbuffer.append(s1); outbuffer.writeLine(chbuffer); chbuffer.clear(); chbuffer.append(s2); outbuffer.writeLine(chbuffer); chbuffer.clear(); chbuffer.append(s3); outbuffer.writeLine(chbuffer); } outbuffer.flush(); final long bytesWritten = outbuffer.getMetrics().getBytesTransferred(); final long expected = ((s1.getBytes("UTF-8").length + 2)+ (s2.getBytes("UTF-8").length + 2) + (s3.getBytes("UTF-8").length + 2)) * 10; Assert.assertEquals(expected, bytesWritten); final SessionInputBufferMock inbuffer = new SessionInputBufferMock( outbuffer.getData(), Consts.UTF_8); for (int i = 0; i < 10; i++) { Assert.assertEquals(s1, inbuffer.readLine()); Assert.assertEquals(s2, inbuffer.readLine()); Assert.assertEquals(s3, inbuffer.readLine()); } Assert.assertNull(inbuffer.readLine()); Assert.assertNull(inbuffer.readLine()); final long bytesRead = inbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(expected, bytesRead); } @Test public void testMultibyteCodedReadWriteLongLine() throws Exception { final String s1 = constructString(SWISS_GERMAN_HELLO); final String s2 = constructString(RUSSIAN_HELLO); final String s3 = "Like hello and stuff"; final StringBuilder buf = new StringBuilder(); for (int i = 0; i < 1024; i++) { buf.append(s1).append(s2).append(s3); } final String s = buf.toString(); final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(Consts.UTF_8); final CharArrayBuffer chbuffer = new CharArrayBuffer(16); chbuffer.append(s); outbuffer.writeLine(chbuffer); outbuffer.flush(); final SessionInputBufferMock inbuffer = new SessionInputBufferMock( outbuffer.getData(), Consts.UTF_8); Assert.assertEquals(s, inbuffer.readLine()); } @Test public void testNonAsciiReadWriteLine() throws Exception { final String s1 = constructString(SWISS_GERMAN_HELLO); final SessionOutputBufferMock outbuffer = new SessionOutputBufferMock(Consts.ISO_8859_1); final CharArrayBuffer chbuffer = new CharArrayBuffer(16); for (int i = 0; i < 5; i++) { chbuffer.clear(); chbuffer.append(s1); outbuffer.writeLine(chbuffer); } for (int i = 0; i < 5; i++) { outbuffer.writeLine(s1); } chbuffer.clear(); outbuffer.writeLine(chbuffer); outbuffer.flush(); final long bytesWritten = outbuffer.getMetrics().getBytesTransferred(); final long expected = ((s1.toString().getBytes(Consts.ISO_8859_1.name()).length + 2)) * 10 + 2; Assert.assertEquals(expected, bytesWritten); final SessionInputBufferMock inbuffer = new SessionInputBufferMock( outbuffer.getData(), Consts.ISO_8859_1); final CharArrayBuffer buf = new CharArrayBuffer(64); for (int i = 0; i < 10; i++) { buf.clear(); final int len = inbuffer.readLine(buf); Assert.assertEquals(len, SWISS_GERMAN_HELLO.length); Assert.assertEquals(s1, buf.toString()); } buf.clear(); Assert.assertEquals("", inbuffer.readLine()); Assert.assertNull(inbuffer.readLine()); Assert.assertNull(inbuffer.readLine()); final long bytesRead = inbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(expected, bytesRead); } @Test(expected=CharacterCodingException.class) public void testUnmappableInputActionReport() throws Exception { final String s = "This text contains a circumflex \u0302 !!!"; final CharsetEncoder encoder = Consts.ISO_8859_1.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE); encoder.onUnmappableCharacter(CodingErrorAction.REPORT); final SessionOutputBufferMock outbuf = new SessionOutputBufferMock(encoder); outbuf.writeLine(s); } @Test public void testUnmappableInputActionReplace() throws Exception { final String s = "This text contains a circumflex \u0302 !!!"; final CharsetEncoder encoder = Consts.ISO_8859_1.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE); encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); final SessionOutputBufferMock outbuf = new SessionOutputBufferMock(encoder); outbuf.writeLine(s); outbuf.flush(); final String result = new String(outbuf.getData(), "ISO-8859-1"); Assert.assertEquals("This text contains a circumflex ? !!!\r\n", result); } @Test public void testUnmappableInputActionIgnore() throws Exception { final String s = "This text contains a circumflex \u0302 !!!"; final CharsetEncoder encoder = Consts.ISO_8859_1.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE); encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); final SessionOutputBufferMock outbuf = new SessionOutputBufferMock(encoder); outbuf.writeLine(s); outbuf.flush(); final String result = new String(outbuf.getData(), "ISO-8859-1"); Assert.assertEquals("This text contains a circumflex !!!\r\n", result); } @Test(expected=CharacterCodingException.class) public void testMalformedInputActionReport() throws Exception { final byte[] tmp = constructString(SWISS_GERMAN_HELLO).getBytes(Consts.ISO_8859_1.name()); final CharsetDecoder decoder = Consts.UTF_8.newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); final SessionInputBufferMock inbuffer = new SessionInputBufferMock(tmp, decoder); inbuffer.readLine(); } @Test public void testMalformedInputActionReplace() throws Exception { final byte[] tmp = constructString(SWISS_GERMAN_HELLO).getBytes(Consts.ISO_8859_1.name()); final CharsetDecoder decoder = Consts.UTF_8.newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPLACE); decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); final SessionInputBufferMock inbuffer = new SessionInputBufferMock(tmp, decoder); final String s = inbuffer.readLine(); Assert.assertEquals("Gr\ufffdezi_z\ufffdm\ufffd", s); } @Test public void testMalformedInputActionIgnore() throws Exception { final byte[] tmp = constructString(SWISS_GERMAN_HELLO).getBytes(Consts.ISO_8859_1.name()); final CharsetDecoder decoder = Consts.UTF_8.newDecoder(); decoder.onMalformedInput(CodingErrorAction.IGNORE); decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); final SessionInputBufferMock inbuffer = new SessionInputBufferMock(tmp, decoder); final String s = inbuffer.readLine(); Assert.assertEquals("Grezi_zm", s); } @Test public void testInvalidCharArrayBuffer() throws Exception { final SessionInputBufferMock inbuffer = new SessionInputBufferMock(new byte[] {}); try { inbuffer.readLine(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { //expected final long bytesRead = inbuffer.getMetrics().getBytesTransferred(); Assert.assertEquals(0, bytesRead); } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/io/TestChunkCoding.java0100644 0000000 0000000 00000044520 12276755421 031057 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import org.apache.http.Header; import org.apache.http.MalformedChunkCodingException; import org.apache.http.TruncatedChunkException; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.impl.SessionOutputBufferMock; import org.apache.http.io.SessionInputBuffer; import org.apache.http.util.EncodingUtils; import org.junit.Assert; import org.junit.Test; public class TestChunkCoding { private static final String CONTENT_CHARSET = "ISO-8859-1"; @Test public void testConstructors() throws Exception { try { new ChunkedInputStream((SessionInputBuffer)null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } new MalformedChunkCodingException(); new MalformedChunkCodingException(""); } private final static String CHUNKED_INPUT = "10;key=\"value\"\r\n1234567890123456\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n"; private final static String CHUNKED_RESULT = "123456789012345612345"; // Test for when buffer is larger than chunk size @Test public void testChunkedInputStreamLargeBuffer() throws IOException { final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(CHUNKED_INPUT, CONTENT_CHARSET))); final byte[] buffer = new byte[300]; final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } Assert.assertEquals(-1, in.read(buffer)); Assert.assertEquals(-1, in.read(buffer)); in.close(); final String result = EncodingUtils.getString(out.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(result, CHUNKED_RESULT); final Header[] footers = in.getFooters(); Assert.assertNotNull(footers); Assert.assertEquals(2, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde", footers[0].getValue()); Assert.assertEquals("Footer2", footers[1].getName()); Assert.assertEquals("fghij", footers[1].getValue()); } //Test for when buffer is smaller than chunk size. @Test public void testChunkedInputStreamSmallBuffer() throws IOException { final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(CHUNKED_INPUT, CONTENT_CHARSET))); final byte[] buffer = new byte[7]; final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } Assert.assertEquals(-1, in.read(buffer)); Assert.assertEquals(-1, in.read(buffer)); in.close(); EncodingUtils.getString(out.toByteArray(), CONTENT_CHARSET); final Header[] footers = in.getFooters(); Assert.assertNotNull(footers); Assert.assertEquals(2, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde", footers[0].getValue()); Assert.assertEquals("Footer2", footers[1].getName()); Assert.assertEquals("fghij", footers[1].getValue()); } // One byte read @Test public void testChunkedInputStreamOneByteRead() throws IOException { final String s = "5\r\n01234\r\n5\r\n56789\r\n0\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); int ch; int i = '0'; while ((ch = in.read()) != -1) { Assert.assertEquals(i, ch); i++; } Assert.assertEquals(-1, in.read()); Assert.assertEquals(-1, in.read()); in.close(); } @Test public void testAvailable() throws IOException { final String s = "5\r\n12345\r\n0\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(4, in.available()); in.close(); } @Test public void testChunkedInputStreamClose() throws IOException { final String s = "5\r\n01234\r\n5\r\n56789\r\n0\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); in.close(); in.close(); try { in.read(); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } final byte[] tmp = new byte[10]; try { in.read(tmp); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } try { in.read(tmp, 0, tmp.length); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } } @Test public void testChunkedOutputStreamClose() throws IOException { final ChunkedOutputStream out = new ChunkedOutputStream( 2048, new SessionOutputBufferMock()); out.close(); out.close(); try { out.write(new byte[] {1,2,3}); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } try { out.write(1); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { // expected } } // Missing closing chunk @Test public void testChunkedInputStreamNoClosingChunk() throws IOException { final String s = "5\r\n01234\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); final byte[] tmp = new byte[5]; Assert.assertEquals(5, in.read(tmp)); Assert.assertEquals(-1, in.read()); in.close(); } // Missing \r\n at the end of the first chunk @Test public void testCorruptChunkedInputStreamMissingCRLF() throws IOException { final String s = "5\r\n012345\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); final byte[] buffer = new byte[300]; final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; try { while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } } // Missing LF @Test public void testCorruptChunkedInputStreamMissingLF() throws IOException { final String s = "5\r01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } in.close(); } // Invalid chunk size @Test public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\r\n01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } try { in.close(); } catch (TruncatedChunkException expected) { } } // Negative chunk size @Test public void testCorruptChunkedInputStreamNegativeSize() throws IOException { final String s = "-5\r\n01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } try { in.close(); } catch (TruncatedChunkException expected) { } } // Truncated chunk @Test public void testCorruptChunkedInputStreamTruncatedChunk() throws IOException { final String s = "3\r\n12"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); final byte[] buffer = new byte[300]; Assert.assertEquals(2, in.read(buffer)); try { in.read(buffer); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } in.close(); } // Invalid footer @Test public void testCorruptChunkedInputStreamInvalidFooter() throws IOException { final String s = "1\r\n0\r\n0\r\nstuff\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } in.close(); } @Test public void testEmptyChunkedInputStream() throws IOException { final String input = "0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(input, CONTENT_CHARSET))); final byte[] buffer = new byte[300]; final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } Assert.assertEquals(0, out.size()); in.close(); } @Test public void testChunkedConsistence() throws IOException { final String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer)); out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET)); out.flush(); out.close(); out.close(); buffer.close(); final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( buffer.toByteArray())); final byte[] d = new byte[10]; final ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } final String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(input, output); in.close(); } @Test public void testChunkedOutputStream() throws IOException { final SessionOutputBufferMock buffer = new SessionOutputBufferMock(); final ChunkedOutputStream out = new ChunkedOutputStream(2, buffer); out.write('1'); out.write('2'); out.write('3'); out.write('4'); out.finish(); out.close(); final byte [] rawdata = buffer.getData(); Assert.assertEquals(19, rawdata.length); Assert.assertEquals('2', rawdata[0]); Assert.assertEquals('\r', rawdata[1]); Assert.assertEquals('\n', rawdata[2]); Assert.assertEquals('1', rawdata[3]); Assert.assertEquals('2', rawdata[4]); Assert.assertEquals('\r', rawdata[5]); Assert.assertEquals('\n', rawdata[6]); Assert.assertEquals('2', rawdata[7]); Assert.assertEquals('\r', rawdata[8]); Assert.assertEquals('\n', rawdata[9]); Assert.assertEquals('3', rawdata[10]); Assert.assertEquals('4', rawdata[11]); Assert.assertEquals('\r', rawdata[12]); Assert.assertEquals('\n', rawdata[13]); Assert.assertEquals('0', rawdata[14]); Assert.assertEquals('\r', rawdata[15]); Assert.assertEquals('\n', rawdata[16]); Assert.assertEquals('\r', rawdata[17]); Assert.assertEquals('\n', rawdata[18]); } @Test public void testChunkedOutputStreamLargeChunk() throws IOException { final SessionOutputBufferMock buffer = new SessionOutputBufferMock(); final ChunkedOutputStream out = new ChunkedOutputStream(2, buffer); out.write(new byte[] {'1', '2', '3', '4'}); out.finish(); out.close(); final byte [] rawdata = buffer.getData(); Assert.assertEquals(14, rawdata.length); Assert.assertEquals('4', rawdata[0]); Assert.assertEquals('\r', rawdata[1]); Assert.assertEquals('\n', rawdata[2]); Assert.assertEquals('1', rawdata[3]); Assert.assertEquals('2', rawdata[4]); Assert.assertEquals('3', rawdata[5]); Assert.assertEquals('4', rawdata[6]); Assert.assertEquals('\r', rawdata[7]); Assert.assertEquals('\n', rawdata[8]); Assert.assertEquals('0', rawdata[9]); Assert.assertEquals('\r', rawdata[10]); Assert.assertEquals('\n', rawdata[11]); Assert.assertEquals('\r', rawdata[12]); Assert.assertEquals('\n', rawdata[13]); } @Test public void testChunkedOutputStreamSmallChunk() throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ChunkedOutputStream out = new ChunkedOutputStream(2, new SessionOutputBufferMock(buffer)); out.write('1'); out.finish(); out.close(); final byte [] rawdata = buffer.toByteArray(); Assert.assertEquals(11, rawdata.length); Assert.assertEquals('1', rawdata[0]); Assert.assertEquals('\r', rawdata[1]); Assert.assertEquals('\n', rawdata[2]); Assert.assertEquals('1', rawdata[3]); Assert.assertEquals('\r', rawdata[4]); Assert.assertEquals('\n', rawdata[5]); Assert.assertEquals('0', rawdata[6]); Assert.assertEquals('\r', rawdata[7]); Assert.assertEquals('\n', rawdata[8]); Assert.assertEquals('\r', rawdata[9]); Assert.assertEquals('\n', rawdata[10]); } @Test public void testResumeOnSocketTimeoutInData() throws IOException { final String s = "5\r\n01234\r\n5\r\n5\0006789\r\na\r\n0123\000456789\r\n0\r\n"; final SessionInputBuffer sessbuf = new SessionInputBufferMock( new TimeoutByteArrayInputStream(s.getBytes("ISO-8859-1")), 16); final InputStream in = new ChunkedInputStream(sessbuf); final byte[] tmp = new byte[3]; int bytesRead = 0; int timeouts = 0; int i = 0; while (i != -1) { try { i = in.read(tmp); if (i > 0) { bytesRead += i; } } catch (final InterruptedIOException ex) { timeouts++; } } Assert.assertEquals(20, bytesRead); Assert.assertEquals(2, timeouts); in.close(); } @Test public void testResumeOnSocketTimeoutInChunk() throws IOException { final String s = "5\000\r\000\n\00001234\r\n\0005\r\n56789\r\na\r\n0123456789\r\n\0000\r\n"; final SessionInputBuffer sessbuf = new SessionInputBufferMock( new TimeoutByteArrayInputStream(s.getBytes("ISO-8859-1")), 16); final InputStream in = new ChunkedInputStream(sessbuf); final byte[] tmp = new byte[3]; int bytesRead = 0; int timeouts = 0; int i = 0; while (i != -1) { try { i = in.read(tmp); if (i > 0) { bytesRead += i; } } catch (final InterruptedIOException ex) { timeouts++; } } Assert.assertEquals(20, bytesRead); Assert.assertEquals(5, timeouts); in.close(); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/pool/0040755 0000000 0000000 00000000000 12276755420 025517 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/impl/pool/TestBasicConnPool.java0100644 0000000 0000000 00000010001 12276755420 031700 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.impl.pool; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.ServerSocket; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocketFactory; import org.apache.http.HttpClientConnection; import org.apache.http.HttpHost; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.SocketConfig; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestBasicConnPool { private BasicConnFactory connFactory; private BasicConnPool pool; private HttpHost host; private HttpClientConnection conn; private ServerSocket server; private int serverPort; private int sslServerPort; @Before public void setUp() throws Exception { // setup an "http" server server = new ServerSocket(0); serverPort = server.getLocalPort(); // setup an "https" server final SSLServerSocket sslServer = (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(0); sslServerPort = sslServer.getLocalPort(); final SocketConfig sconfig = SocketConfig.custom().setSoTimeout(100).build(); connFactory = new BasicConnFactory(sconfig, ConnectionConfig.DEFAULT); pool = new BasicConnPool(connFactory); } @After public void tearDown() throws Exception { server.close(); if(conn != null) { conn.close(); } } @Test(expected=IllegalArgumentException.class) public void testNullConstructor2() throws Exception { new BasicConnPool((BasicConnFactory) null); } @Test public void testHttpCreateConnection() throws Exception { host = new HttpHost("localhost", serverPort, "http"); conn = connFactory.create(host); assertTrue(conn.isOpen()); assertEquals(100, conn.getSocketTimeout()); } @Test public void testHttpsCreateConnection() throws Exception { final SocketConfig sconfig = SocketConfig.custom().setSoTimeout(100).build(); connFactory = new BasicConnFactory( null, (SSLSocketFactory)SSLSocketFactory.getDefault(), 0, sconfig, ConnectionConfig.DEFAULT); host = new HttpHost("localhost", sslServerPort, "https"); conn = connFactory.create(host); assertTrue(conn.isOpen()); assertEquals(100, conn.getSocketTimeout()); } @Test public void testHttpCreateEntry() throws Exception { host = new HttpHost("localhost", serverPort, "http"); conn = connFactory.create(host); final BasicPoolEntry entry = pool.createEntry(host, conn); assertEquals(conn, entry.getConnection()); assertEquals("localhost", entry.getRoute().getHostName()); entry.close(); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/config/0040755 0000000 0000000 00000000000 12276755422 025054 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/config/TestRegistry.java0100644 0000000 0000000 00000003241 12276755422 030364 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.config; import org.junit.Assert; import org.junit.Test; public class TestRegistry { @Test public void testCompleted() throws Exception { final Registry reg = RegistryBuilder.create().register("Stuff", "Stuff").build(); Assert.assertEquals("Stuff", reg.lookup("Stuff")); Assert.assertEquals("Stuff", reg.lookup("stuff")); Assert.assertEquals(null, reg.lookup("miss")); Assert.assertEquals(null, reg.lookup(null)); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/0040755 0000000 0000000 00000000000 12276755421 025447 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000150 12276757361 011647 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestStandardInterceptors.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestStandardInterceptors.j0100644 0000000 0000000 00000133543 12276755421 032632 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.net.InetAddress; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpInetConnection; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestStandardInterceptors { @Test public void testRequestConnControlGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final RequestConnControl interceptor = new RequestConnControl(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.CONN_KEEP_ALIVE, header.getValue()); } @Test public void testRequestConnControlConnectMethod() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("CONNECT", "/"); final RequestConnControl interceptor = new RequestConnControl(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNull(header); } @Test public void testRequestConnControlCustom() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final Header myheader = new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); request.addHeader(myheader); final RequestConnControl interceptor = new RequestConnControl(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.CONN_CLOSE, header.getValue()); Assert.assertTrue(header == myheader); } @Test public void testRequestConnControlInvalidInput() throws Exception { final RequestConnControl interceptor = new RequestConnControl(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testRequestContentProtocolException() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request1 = new BasicHttpEntityEnclosingRequest("POST", "/"); request1.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "chunked")); final BasicHttpRequest request2 = new BasicHttpEntityEnclosingRequest("POST", "/"); request2.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "12")); final RequestContent interceptor = new RequestContent(); try { interceptor.process(request1, context); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } try { interceptor.process(request2, context); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } } @Test public void testRequestContentNullEntity() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final RequestContent interceptor = new RequestContent(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNotNull(header); Assert.assertEquals("0", header.getValue()); Assert.assertNull(request.getFirstHeader(HTTP.TRANSFER_ENCODING)); } @Test public void testRequestContentEntityContentLengthDelimitedHTTP11() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final String s = "whatever"; final StringEntity entity = new StringEntity(s, "US-ASCII"); request.setEntity(entity); final RequestContent interceptor = new RequestContent(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNotNull(header); Assert.assertEquals(s.length(), Integer.parseInt(header.getValue())); Assert.assertNull(request.getFirstHeader(HTTP.TRANSFER_ENCODING)); } @Test public void testRequestContentEntityChunkedHTTP11() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final String s = "whatever"; final StringEntity entity = new StringEntity(s, "US-ASCII"); entity.setChunked(true); request.setEntity(entity); final RequestContent interceptor = new RequestContent(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.TRANSFER_ENCODING); Assert.assertNotNull(header); Assert.assertEquals("chunked", header.getValue()); Assert.assertNull(request.getFirstHeader(HTTP.CONTENT_LEN)); } @Test public void testRequestContentEntityUnknownLengthHTTP11() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentLength(-1); entity.setChunked(false); request.setEntity(entity); final RequestContent interceptor = new RequestContent(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.TRANSFER_ENCODING); Assert.assertNotNull(header); Assert.assertEquals("chunked", header.getValue()); Assert.assertNull(request.getFirstHeader(HTTP.CONTENT_LEN)); } @Test public void testRequestContentEntityChunkedHTTP10() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", "/", HttpVersion.HTTP_1_0); final String s = "whatever"; final StringEntity entity = new StringEntity(s, "US-ASCII"); entity.setChunked(true); request.setEntity(entity); final RequestContent interceptor = new RequestContent(); try { interceptor.process(request, context); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } } @Test public void testRequestContentTypeAndEncoding() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentType("whatever"); entity.setContentEncoding("whatever"); request.setEntity(entity); final RequestContent interceptor = new RequestContent(); interceptor.process(request, context); final Header h1 = request.getFirstHeader(HTTP.CONTENT_TYPE); Assert.assertNotNull(h1); Assert.assertEquals("whatever", h1.getValue()); final Header h2 = request.getFirstHeader(HTTP.CONTENT_ENCODING); Assert.assertNotNull(h2); Assert.assertEquals("whatever", h2.getValue()); } @Test public void testRequestContentNullTypeAndEncoding() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final BasicHttpEntity entity = new BasicHttpEntity(); request.setEntity(entity); final RequestContent interceptor = new RequestContent(); interceptor.process(request, context); Assert.assertNull(request.getFirstHeader(HTTP.CONTENT_TYPE)); Assert.assertNull(request.getFirstHeader(HTTP.CONTENT_ENCODING)); } @Test public void testRequestContentEntityUnknownLengthHTTP10() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", "/", HttpVersion.HTTP_1_0); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentLength(-1); entity.setChunked(false); request.setEntity(entity); final RequestContent interceptor = new RequestContent(); try { interceptor.process(request, context); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } } @Test public void testRequestContentInvalidInput() throws Exception { final RequestContent interceptor = new RequestContent(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testRequestContentIgnoreNonenclosingRequests() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("POST", "/"); final RequestContent interceptor = new RequestContent(); interceptor.process(request, context); Assert.assertEquals(0, request.getAllHeaders().length); } @Test public void testRequestContentOverwriteHeaders() throws Exception { final RequestContent interceptor = new RequestContent(true); final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10")); request.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "whatever")); interceptor.process(request, context); Assert.assertEquals("0", request.getFirstHeader(HTTP.CONTENT_LEN).getValue()); } @Test public void testRequestContentAddHeaders() throws Exception { final RequestContent interceptor = new RequestContent(true); final HttpContext context = new BasicHttpContext(null); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); interceptor.process(request, context); Assert.assertEquals("0", request.getFirstHeader(HTTP.CONTENT_LEN).getValue()); Assert.assertNull(request.getFirstHeader(HTTP.TRANSFER_ENCODING)); } @Test public void testRequestExpectContinueGenerated() throws Exception { final HttpCoreContext context = HttpCoreContext.create(); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final String s = "whatever"; final StringEntity entity = new StringEntity(s, "US-ASCII"); request.setEntity(entity); final RequestExpectContinue interceptor = new RequestExpectContinue(true); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.EXPECT_CONTINUE, header.getValue()); } @Test public void testRequestExpectContinueHTTP10() throws Exception { final HttpCoreContext context = HttpCoreContext.create(); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", "/", HttpVersion.HTTP_1_0); final String s = "whatever"; final StringEntity entity = new StringEntity(s, "US-ASCII"); request.setEntity(entity); final RequestExpectContinue interceptor = new RequestExpectContinue(true); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE); Assert.assertNull(header); } @Test public void testRequestExpectContinueZeroContent() throws Exception { final HttpCoreContext context = HttpCoreContext.create(); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final String s = ""; final StringEntity entity = new StringEntity(s, "US-ASCII"); request.setEntity(entity); final RequestExpectContinue interceptor = new RequestExpectContinue(true); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE); Assert.assertNull(header); } @Test public void testRequestExpectContinueInvalidInput() throws Exception { final RequestExpectContinue interceptor = new RequestExpectContinue(true); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testRequestExpectContinueIgnoreNonenclosingRequests() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("POST", "/"); final RequestExpectContinue interceptor = new RequestExpectContinue(true); interceptor.process(request, context); Assert.assertEquals(0, request.getAllHeaders().length); } @Test public void testRequestTargetHostGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpHost host = new HttpHost("somehost", 8080, "http"); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, host); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final RequestTargetHost interceptor = new RequestTargetHost(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.TARGET_HOST); Assert.assertNotNull(header); Assert.assertEquals("somehost:8080", header.getValue()); } @Test public void testRequestTargetHostFallback() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final InetAddress address = Mockito.mock(InetAddress.class); Mockito.when(address.getHostName()).thenReturn("somehost"); final HttpInetConnection conn = Mockito.mock(HttpInetConnection.class); Mockito.when(conn.getRemoteAddress()).thenReturn(address); Mockito.when(conn.getRemotePort()).thenReturn(1234); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, null); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); final RequestTargetHost interceptor = new RequestTargetHost(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.TARGET_HOST); Assert.assertNotNull(header); Assert.assertEquals("somehost:1234", header.getValue()); } @Test(expected=ProtocolException.class) public void testRequestTargetHostFallbackFailure() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final HttpInetConnection conn = Mockito.mock(HttpInetConnection.class); Mockito.when(conn.getRemoteAddress()).thenReturn(null); Mockito.when(conn.getRemotePort()).thenReturn(1234); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, null); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); final RequestTargetHost interceptor = new RequestTargetHost(); interceptor.process(request, context); } @Test public void testRequestTargetHostNotGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpHost host = new HttpHost("somehost", 8080, "http"); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, host); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader(new BasicHeader(HTTP.TARGET_HOST, "whatever")); final RequestTargetHost interceptor = new RequestTargetHost(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.TARGET_HOST); Assert.assertNotNull(header); Assert.assertEquals("whatever", header.getValue()); } @Test public void testRequestTargetHostMissingHostHTTP10() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest( "GET", "/", HttpVersion.HTTP_1_0); final RequestTargetHost interceptor = new RequestTargetHost(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.TARGET_HOST); Assert.assertNull(header); } @Test public void testRequestTargetHostMissingHostHTTP11() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final RequestTargetHost interceptor = new RequestTargetHost(); try { interceptor.process(request, context); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } } @Test public void testRequestTargetHostInvalidInput() throws Exception { final RequestTargetHost interceptor = new RequestTargetHost(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { interceptor.process(new BasicHttpRequest("GET", "/"), null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testRequestTargetHostConnectHttp11() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpHost host = new HttpHost("somehost", 8080, "http"); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, host); final BasicHttpRequest request = new BasicHttpRequest("CONNECT", "/"); final RequestTargetHost interceptor = new RequestTargetHost(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.TARGET_HOST); Assert.assertNotNull(header); Assert.assertEquals("somehost:8080", header.getValue()); } @Test public void testRequestTargetHostConnectHttp10() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpHost host = new HttpHost("somehost", 8080, "http"); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, host); final BasicHttpRequest request = new BasicHttpRequest("CONNECT", "/", HttpVersion.HTTP_1_0); final RequestTargetHost interceptor = new RequestTargetHost(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.TARGET_HOST); Assert.assertNull(header); } @Test public void testRequestUserAgentGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final RequestUserAgent interceptor = new RequestUserAgent("some agent"); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.USER_AGENT); Assert.assertNotNull(header); Assert.assertEquals("some agent", header.getValue()); } @Test public void testRequestUserAgentNotGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader(new BasicHeader(HTTP.USER_AGENT, "whatever")); final RequestUserAgent interceptor = new RequestUserAgent("some agent"); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.USER_AGENT); Assert.assertNotNull(header); Assert.assertEquals("whatever", header.getValue()); } @Test public void testRequestUserAgentMissingUserAgent() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final RequestUserAgent interceptor = new RequestUserAgent(); interceptor.process(request, context); final Header header = request.getFirstHeader(HTTP.USER_AGENT); Assert.assertNull(header); } @Test public void testRequestUserAgentInvalidInput() throws Exception { final RequestUserAgent interceptor = new RequestUserAgent(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testResponseConnControlNoEntity() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final ResponseConnControl interceptor = new ResponseConnControl(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNull(header); } @Test public void testResponseConnControlEntityContentLength() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final StringEntity entity = new StringEntity("whatever"); response.setEntity(entity); final ResponseConnControl interceptor = new ResponseConnControl(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNull(header); } @Test public void testResponseConnControlEntityUnknownContentLength() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); response.setEntity(entity); final ResponseConnControl interceptor = new ResponseConnControl(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.CONN_CLOSE, header.getValue()); } @Test public void testResponseConnControlEntityChunked() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setChunked(true); response.setEntity(entity); final ResponseConnControl interceptor = new ResponseConnControl(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNull(header); } @Test public void testResponseConnControlEntityUnknownContentLengthHTTP10() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); final BasicHttpResponse response = new BasicHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); response.setEntity(entity); final ResponseConnControl interceptor = new ResponseConnControl(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.CONN_CLOSE, header.getValue()); } @Test public void testResponseConnControlClientRequest() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final StringEntity entity = new StringEntity("whatever"); response.setEntity(entity); final ResponseConnControl interceptor = new ResponseConnControl(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.CONN_KEEP_ALIVE, header.getValue()); } @Test public void testResponseConnControlClientRequest2() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final StringEntity entity = new StringEntity("whatever"); response.setEntity(entity); final ResponseConnControl interceptor = new ResponseConnControl(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNull(header); } @Test public void testResponseConnControl10Client11Response() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_0); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final StringEntity entity = new StringEntity("whatever"); response.setEntity(entity); final ResponseConnControl interceptor = new ResponseConnControl(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.CONN_CLOSE, header.getValue()); } @Test public void testResponseConnControlStatusCode() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); final ResponseConnControl interceptor = new ResponseConnControl(); final int [] statusCodes = new int[] { HttpStatus.SC_BAD_REQUEST, HttpStatus.SC_REQUEST_TIMEOUT, HttpStatus.SC_LENGTH_REQUIRED, HttpStatus.SC_REQUEST_TOO_LONG, HttpStatus.SC_REQUEST_URI_TOO_LONG, HttpStatus.SC_SERVICE_UNAVAILABLE, HttpStatus.SC_NOT_IMPLEMENTED }; for (final int statusCode : statusCodes) { final BasicHttpResponse response = new BasicHttpResponse( HttpVersion.HTTP_1_1, statusCode, "Unreasonable"); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.CONN_CLOSE, header.getValue()); } } @Test public void testResponseConnControlExplicitClose() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); final ResponseConnControl interceptor = new ResponseConnControl(); final BasicHttpResponse response = new BasicHttpResponse( HttpVersion.HTTP_1_1, 200, "OK"); response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.CONN_CLOSE, header.getValue()); } @Test public void testResponseConnControlHostInvalidInput() throws Exception { final ResponseConnControl interceptor = new ResponseConnControl(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); interceptor.process(response, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testResponseContentNoEntity() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNotNull(header); Assert.assertEquals("0", header.getValue()); } @Test public void testResponseContentStatusNoContent() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.setStatusCode(HttpStatus.SC_NO_CONTENT); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNull(header); } @Test public void testResponseContentStatusResetContent() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.setStatusCode(HttpStatus.SC_RESET_CONTENT); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNull(header); } @Test public void testResponseContentStatusNotModified() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header header = response.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNull(header); } @Test public void testResponseContentEntityChunked() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setChunked(true); response.setEntity(entity); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.TRANSFER_ENCODING); Assert.assertNotNull(h1); Assert.assertEquals(HTTP.CHUNK_CODING, h1.getValue()); final Header h2 = response.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNull(h2); } @Test public void testResponseContentEntityContentLenghtDelimited() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentLength (10); response.setEntity(entity); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNotNull(h1); Assert.assertEquals("10", h1.getValue()); final Header h2 = response.getFirstHeader(HTTP.TRANSFER_ENCODING); Assert.assertNull(h2); } @Test public void testResponseContentEntityUnknownContentLength() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); response.setEntity(entity); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.TRANSFER_ENCODING); Assert.assertNull(h1); final Header h2 = response.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNull(h2); } @Test public void testResponseContentEntityChunkedHTTP10() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setChunked(true); response.setEntity(entity); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.TRANSFER_ENCODING); Assert.assertNull(h1); final Header h2 = response.getFirstHeader(HTTP.CONTENT_LEN); Assert.assertNull(h2); } @Test public void testResponseContentEntityNoContentTypeAndEncoding() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); response.setEntity(entity); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.CONTENT_TYPE); Assert.assertNull(h1); final Header h2 = response.getFirstHeader(HTTP.CONTENT_ENCODING); Assert.assertNull(h2); } @Test public void testResponseContentEntityContentTypeAndEncoding() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentEncoding("whatever"); entity.setContentType("whatever"); response.setEntity(entity); final ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.CONTENT_TYPE); Assert.assertNotNull(h1); Assert.assertEquals("whatever", h1.getValue()); final Header h2 = response.getFirstHeader(HTTP.CONTENT_ENCODING); Assert.assertNotNull(h2); Assert.assertEquals("whatever", h2.getValue()); } @Test public void testResponseContentInvalidInput() throws Exception { final ResponseContent interceptor = new ResponseContent(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testResponseContentInvalidResponseState() throws Exception { final ResponseContent interceptor = new ResponseContent(); final HttpContext context = new BasicHttpContext(null); try { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10")); interceptor.process(response, context); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } try { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "stuff")); interceptor.process(response, context); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { // expected } } @Test public void testResponseContentOverwriteHeaders() throws Exception { final ResponseContent interceptor = new ResponseContent(true); final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10")); response.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "whatever")); interceptor.process(response, context); Assert.assertEquals("0", response.getFirstHeader(HTTP.CONTENT_LEN).getValue()); } @Test public void testResponseContentAddHeaders() throws Exception { final ResponseContent interceptor = new ResponseContent(true); final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); interceptor.process(response, context); Assert.assertEquals("0", response.getFirstHeader(HTTP.CONTENT_LEN).getValue()); Assert.assertNull(response.getFirstHeader(HTTP.TRANSFER_ENCODING)); } @Test public void testResponseDateGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final ResponseDate interceptor = new ResponseDate(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.DATE_HEADER); Assert.assertNotNull(h1); interceptor.process(response, context); final Header h2 = response.getFirstHeader(HTTP.DATE_HEADER); Assert.assertNotNull(h2); } @Test public void testResponseDateNotGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.setStatusCode(199); final ResponseDate interceptor = new ResponseDate(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.DATE_HEADER); Assert.assertNull(h1); } @Test public void testResponseDateInvalidInput() throws Exception { final ResponseDate interceptor = new ResponseDate(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testRequestDateGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); //BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final RequestDate interceptor = new RequestDate(); interceptor.process(request, context); final Header h1 = request.getFirstHeader(HTTP.DATE_HEADER); Assert.assertNotNull(h1); interceptor.process(request, context); final Header h2 = request.getFirstHeader(HTTP.DATE_HEADER); Assert.assertNotNull(h2); } @Test public void testRequestDateNotGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final RequestDate interceptor = new RequestDate(); interceptor.process(request, context); final Header h1 = request.getFirstHeader(HTTP.DATE_HEADER); Assert.assertNull(h1); } @Test public void testRequestDateInvalidInput() throws Exception { final RequestDate interceptor = new RequestDate(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testResponseServerGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final ResponseServer interceptor = new ResponseServer("some server"); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.SERVER_HEADER); Assert.assertNotNull(h1); Assert.assertEquals("some server", h1.getValue()); } @Test public void testResponseServerNotGenerated() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader(new BasicHeader(HTTP.SERVER_HEADER, "whatever")); final ResponseServer interceptor = new ResponseServer("some server"); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.SERVER_HEADER); Assert.assertNotNull(h1); Assert.assertEquals("whatever", h1.getValue()); } @Test public void testResponseServerMissing() throws Exception { final HttpContext context = new BasicHttpContext(null); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final ResponseServer interceptor = new ResponseServer(); interceptor.process(response, context); final Header h1 = response.getFirstHeader(HTTP.SERVER_HEADER); Assert.assertNull(h1); } @Test public void testResponseServerInvalidInput() throws Exception { final ResponseServer interceptor = new ResponseServer(); try { interceptor.process(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } ././@LongLink0100644 0000000 0000000 00000000145 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestUriPatternMatcher.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestUriPatternMatcher.java0100644 0000000 0000000 00000011654 12276755421 032557 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.junit.Assert; import org.junit.Test; public class TestUriPatternMatcher { @Test public void testRegisterUnregister() throws Exception { final Object h1 = new Object(); final Object h2 = new Object(); final Object h3 = new Object(); final UriPatternMatcher matcher = new UriPatternMatcher(); matcher.register("/h1", h1); matcher.register("/h2", h2); matcher.register("/h3", h3); Object h; h = matcher.lookup("/h1"); Assert.assertNotNull(h); Assert.assertTrue(h1 == h); h = matcher.lookup("/h2"); Assert.assertNotNull(h); Assert.assertTrue(h2 == h); h = matcher.lookup("/h3"); Assert.assertNotNull(h); Assert.assertTrue(h3 == h); matcher.unregister("/h1"); h = matcher.lookup("/h1"); Assert.assertNull(h); } @Test(expected=IllegalArgumentException.class) public void testRegisterNull() throws Exception { final UriPatternMatcher matcher = new UriPatternMatcher(); matcher.register(null, null); } @Test public void testWildCardMatching1() throws Exception { final Object h1 = new Object(); final Object h2 = new Object(); final Object h3 = new Object(); final Object def = new Object(); final UriPatternMatcher matcher = new UriPatternMatcher(); matcher.register("*", def); matcher.register("/one/*", h1); matcher.register("/one/two/*", h2); matcher.register("/one/two/three/*", h3); Object h; h = matcher.lookup("/one/request"); Assert.assertNotNull(h); Assert.assertTrue(h1 == h); h = matcher.lookup("/one/two/request"); Assert.assertNotNull(h); Assert.assertTrue(h2 == h); h = matcher.lookup("/one/two/three/request"); Assert.assertNotNull(h); Assert.assertTrue(h3 == h); h = matcher.lookup("default/request"); Assert.assertNotNull(h); Assert.assertTrue(def == h); } @Test public void testWildCardMatching2() throws Exception { final Object h1 = new Object(); final Object h2 = new Object(); final Object def = new Object(); final UriPatternMatcher matcher = new UriPatternMatcher(); matcher.register("*", def); matcher.register("*.view", h1); matcher.register("*.form", h2); Object h; h = matcher.lookup("/that.view"); Assert.assertNotNull(h); Assert.assertTrue(h1 == h); h = matcher.lookup("/that.form"); Assert.assertNotNull(h); Assert.assertTrue(h2 == h); h = matcher.lookup("/whatever"); Assert.assertNotNull(h); Assert.assertTrue(def == h); } @Test public void testSuffixPatternOverPrefixPatternMatch() throws Exception { final Object h1 = new Object(); final Object h2 = new Object(); final UriPatternMatcher matcher = new UriPatternMatcher(); matcher.register("/ma*", h1); matcher.register("*tch", h2); Object h; h = matcher.lookup("/match"); Assert.assertNotNull(h); Assert.assertTrue(h1 == h); } @Test(expected=IllegalArgumentException.class) public void testRegisterInvalidInput() throws Exception { final UriPatternMatcher matcher = new UriPatternMatcher(); matcher.register(null, null); } @Test(expected=IllegalArgumentException.class) public void testLookupInvalidInput() throws Exception { final UriPatternMatcher matcher = new UriPatternMatcher(); matcher.lookup(null); } } ././@LongLink0100644 0000000 0000000 00000000147 12276757361 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestHttpRequestExecutor.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestHttpRequestExecutor.ja0100644 0000000 0000000 00000050727 12276755421 032642 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.IOException; import org.apache.http.HttpClientConnection; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestHttpRequestExecutor { @Test public void testInvalidInput() throws Exception { final HttpCoreContext context = HttpCoreContext.create(); final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.execute(null, conn, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.execute(request, null, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.execute(request, conn, null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.doSendRequest(null, conn, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.doSendRequest(request, null, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.doSendRequest(request, conn, null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.doReceiveResponse(null, conn, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.doReceiveResponse(request, null, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.doReceiveResponse(request, conn, null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.preProcess(null, httprocessor, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.preProcess(request, null, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.preProcess(request, httprocessor, null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.postProcess(null, httprocessor, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.postProcess(response, null, context); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { final HttpRequestExecutor executor = new HttpRequestExecutor(); executor.postProcess(response, httprocessor, null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } } @Test public void testBasicExecution() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpRequest request = new BasicHttpRequest("GET", "/"); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK")); final HttpResponse response = executor.execute(request, conn, context); Mockito.verify(conn).sendRequestHeader(request); Mockito.verify(conn).flush(); Mockito.verify(conn).receiveResponseHeader(); Mockito.verify(conn).receiveResponseEntity(response); executor.postProcess(response, httprocessor, context); Mockito.verify(httprocessor).process(response, context); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); } @Test public void testExecutionSkipIntermediateResponses() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpRequest request = new BasicHttpRequest("GET", "/"); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "OK"), new BasicHttpResponse(HttpVersion.HTTP_1_1, 101, "OK"), new BasicHttpResponse(HttpVersion.HTTP_1_1, 102, "OK"), new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK")); final HttpResponse response = executor.execute(request, conn, context); Mockito.verify(conn).sendRequestHeader(request); Mockito.verify(conn).flush(); Mockito.verify(conn, Mockito.times(4)).receiveResponseHeader(); Mockito.verify(conn, Mockito.times(1)).receiveResponseEntity(response); executor.postProcess(response, httprocessor, context); Mockito.verify(httprocessor).process(response, context); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); } @Test public void testExecutionNoResponseBody() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpRequest request = new BasicHttpRequest("GET", "/"); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 204, "OK")); final HttpResponse response = executor.execute(request, conn, context); Mockito.verify(conn).sendRequestHeader(request); Mockito.verify(conn).flush(); Mockito.verify(conn).receiveResponseHeader(); Mockito.verify(conn, Mockito.never()).receiveResponseEntity(response); executor.postProcess(response, httprocessor, context); Mockito.verify(httprocessor).process(response, context); } @Test public void testExecutionHead() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpRequest request = new BasicHttpRequest("HEAD", "/"); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK")); final HttpResponse response = executor.execute(request, conn, context); Mockito.verify(conn).sendRequestHeader(request); Mockito.verify(conn).flush(); Mockito.verify(conn).receiveResponseHeader(); Mockito.verify(conn, Mockito.never()).receiveResponseEntity(response); executor.postProcess(response, httprocessor, context); Mockito.verify(httprocessor).process(response, context); } @Test public void testExecutionEntityEnclosingRequest() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); // request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); final HttpEntity entity = Mockito.mock(HttpEntity.class); request.setEntity(entity); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK")); final HttpResponse response = executor.execute(request, conn, context); Mockito.verify(conn).sendRequestHeader(request); Mockito.verify(conn).sendRequestEntity(request); Mockito.verify(conn).flush(); Mockito.verify(conn).receiveResponseHeader(); Mockito.verify(conn).receiveResponseEntity(response); executor.postProcess(response, httprocessor, context); Mockito.verify(httprocessor).process(response, context); } @Test public void testExecutionEntityEnclosingRequestWithExpectContinueSuccess() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); final HttpEntity entity = Mockito.mock(HttpEntity.class); request.setEntity(entity); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Continue"), new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK")); Mockito.when(conn.isResponseAvailable(Mockito.anyInt())).thenReturn(Boolean.TRUE); final HttpResponse response = executor.execute(request, conn, context); Mockito.verify(conn).sendRequestHeader(request); Mockito.verify(conn).sendRequestEntity(request); Mockito.verify(conn, Mockito.times(2)).flush(); Mockito.verify(conn).isResponseAvailable(3000); Mockito.verify(conn, Mockito.times(2)).receiveResponseHeader(); Mockito.verify(conn).receiveResponseEntity(response); executor.postProcess(response, httprocessor, context); Mockito.verify(httprocessor).process(response, context); Assert.assertEquals(Boolean.TRUE, context.isRequestSent()); } @Test public void testExecutionEntityEnclosingRequestWithExpectContinueFailure() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); final HttpEntity entity = Mockito.mock(HttpEntity.class); request.setEntity(entity); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 402, "OK")); Mockito.when(conn.isResponseAvailable(Mockito.anyInt())).thenReturn(Boolean.TRUE); final HttpResponse response = executor.execute(request, conn, context); Mockito.verify(conn).sendRequestHeader(request); Mockito.verify(conn, Mockito.never()).sendRequestEntity(request); Mockito.verify(conn, Mockito.times(2)).flush(); Mockito.verify(conn).isResponseAvailable(3000); Mockito.verify(conn).receiveResponseHeader(); Mockito.verify(conn).receiveResponseEntity(response); executor.postProcess(response, httprocessor, context); Mockito.verify(httprocessor).process(response, context); } @Test public void testExecutionEntityEnclosingRequestUnsupportedIntermediateResponse() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); final HttpEntity entity = Mockito.mock(HttpEntity.class); request.setEntity(entity); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 101, "OK")); Mockito.when(conn.isResponseAvailable(Mockito.anyInt())).thenReturn(Boolean.TRUE); try { executor.execute(request, conn, context); Assert.fail("ProtocolException should have been thrown"); } catch (final ProtocolException ex) { Mockito.verify(conn).close(); Assert.assertEquals(Boolean.FALSE, context.isRequestSent()); } } @Test public void testExecutionEntityEnclosingRequestWithExpectContinueNoResponse() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); final HttpEntity entity = Mockito.mock(HttpEntity.class); request.setEntity(entity); executor.preProcess(request, httprocessor, context); Mockito.verify(httprocessor).process(request, context); Mockito.when(conn.receiveResponseHeader()).thenReturn( new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK")); Mockito.when(conn.isResponseAvailable(Mockito.anyInt())).thenReturn(Boolean.FALSE); final HttpResponse response = executor.execute(request, conn, context); Mockito.verify(conn).sendRequestHeader(request); Mockito.verify(conn).sendRequestEntity(request); Mockito.verify(conn, Mockito.times(2)).flush(); Mockito.verify(conn).isResponseAvailable(3000); Mockito.verify(conn).receiveResponseHeader(); Mockito.verify(conn).receiveResponseEntity(response); executor.postProcess(response, httprocessor, context); Mockito.verify(httprocessor).process(response, context); } @Test public void testExecutionIOException() throws Exception { final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpRequest request = new BasicHttpRequest("GET", "/"); Mockito.doThrow(new IOException("Oopsie")).when(conn).sendRequestHeader(request); try { executor.execute(request, conn, context); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { Mockito.verify(conn).close(); Assert.assertEquals(Boolean.FALSE, context.isRequestSent()); } } @Test public void testExecutionRuntimeException() throws Exception { final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpCoreContext context = HttpCoreContext.create(); final HttpRequest request = new BasicHttpRequest("GET", "/"); Mockito.doThrow(new RuntimeException("Oopsie")).when(conn).receiveResponseHeader(); try { executor.execute(request, conn, context); Assert.fail("IOException should have been thrown"); } catch (final RuntimeException ex) { Mockito.verify(conn).close(); Assert.assertEquals(Boolean.TRUE, context.isRequestSent()); } } } ././@LongLink0100644 0000000 0000000 00000000150 12276757361 011647 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestHttpExecutionContext.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestHttpExecutionContext.j0100644 0000000 0000000 00000007723 12276755421 032640 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.junit.Assert; import org.junit.Test; // the name of this test is historic, the implementation classes of HttpContext // have been renamed to BasicHttpContext and SyncBasicHttpContext public class TestHttpExecutionContext { @Test public void testContextOperations() { final HttpContext parentContext = new BasicHttpContext(null); final HttpContext currentContext = new BasicHttpContext(parentContext); parentContext.setAttribute("param1", "1"); parentContext.setAttribute("param2", "2"); currentContext.setAttribute("param3", "3"); currentContext.setAttribute("param2", "4"); Assert.assertEquals("1", parentContext.getAttribute("param1")); Assert.assertEquals("2", parentContext.getAttribute("param2")); Assert.assertEquals(null, parentContext.getAttribute("param3")); Assert.assertEquals("1", currentContext.getAttribute("param1")); Assert.assertEquals("4", currentContext.getAttribute("param2")); Assert.assertEquals("3", currentContext.getAttribute("param3")); Assert.assertEquals(null, currentContext.getAttribute("param4")); currentContext.removeAttribute("param1"); currentContext.removeAttribute("param2"); currentContext.removeAttribute("param3"); currentContext.removeAttribute("param4"); Assert.assertEquals("1", currentContext.getAttribute("param1")); Assert.assertEquals("2", currentContext.getAttribute("param2")); Assert.assertEquals(null, currentContext.getAttribute("param3")); Assert.assertEquals(null, currentContext.getAttribute("param4")); } @Test public void testEmptyContextOperations() { final HttpContext currentContext = new BasicHttpContext(null); Assert.assertEquals(null, currentContext.getAttribute("param1")); currentContext.removeAttribute("param1"); Assert.assertEquals(null, currentContext.getAttribute("param1")); } @Test public void testContextInvalidInput() throws Exception { final HttpContext currentContext = new BasicHttpContext(null); try { currentContext.setAttribute(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { currentContext.getAttribute(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { currentContext.removeAttribute(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } ././@LongLink0100644 0000000 0000000 00000000157 12276757361 011656 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestUriHttpRequestHandlerMapper.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestUriHttpRequestHandlerM0100644 0000000 0000000 00000007727 12276755421 032627 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import org.apache.http.HttpRequest; import org.apache.http.message.BasicHttpRequest; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestUriHttpRequestHandlerMapper { @Test public void testRegisterUnregister() throws Exception { final HttpRequestHandler h = Mockito.mock(HttpRequestHandler.class); final UriPatternMatcher matcher = Mockito.spy(new UriPatternMatcher()); final UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper(matcher); registry.register("/h1", h); registry.unregister("/h1"); Mockito.verify(matcher).register("/h1", h); Mockito.verify(matcher).unregister("/h1"); } @Test public void testLookup() throws Exception { final UriPatternMatcher matcher = Mockito.spy(new UriPatternMatcher()); final UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper(matcher); final HttpRequest request = new BasicHttpRequest("GET", "/"); registry.lookup(request); registry.unregister("/h1"); Mockito.verify(matcher).lookup("/"); } @Test(expected=IllegalArgumentException.class) public void testRegisterNull() throws Exception { final UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper(); registry.register(null, null); } @Test(expected=IllegalArgumentException.class) public void testLookupNull() throws Exception { final UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper(); registry.register(null, null); } @Test public void testWildCardMatchingWithQuery() throws Exception { final HttpRequestHandler h1 = Mockito.mock(HttpRequestHandler.class); final HttpRequestHandler h2 = Mockito.mock(HttpRequestHandler.class); final HttpRequestHandler def = Mockito.mock(HttpRequestHandler.class); final UriPatternMatcher matcher = Mockito.spy(new UriPatternMatcher()); final UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper(matcher); registry.register("*", def); registry.register("*.view", h1); registry.register("*.form", h2); HttpRequestHandler h; h = registry.lookup(new BasicHttpRequest("GET", "/that.view?param=value")); Assert.assertNotNull(h); Assert.assertTrue(h1 == h); h = registry.lookup(new BasicHttpRequest("GET", "/that.form?whatever")); Assert.assertNotNull(h); Assert.assertTrue(h2 == h); h = registry.lookup(new BasicHttpRequest("GET", "/whatever")); Assert.assertNotNull(h); Assert.assertTrue(def == h); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestChainBuilder.java0100644 0000000 0000000 00000005100 12276755421 031474 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.util.LinkedList; import java.util.List; import org.apache.http.HttpRequestInterceptor; import org.junit.Assert; import org.junit.Test; public class TestChainBuilder { @Test public void testBuildChain() throws Exception { final ChainBuilder cb = new ChainBuilder(); final HttpRequestInterceptor i1 = new RequestContent(); final HttpRequestInterceptor i2 = new RequestTargetHost(); final HttpRequestInterceptor i3 = new RequestConnControl(); final HttpRequestInterceptor i4 = new RequestUserAgent(); final HttpRequestInterceptor i5 = new RequestExpectContinue(true); cb.addFirst(i1); cb.addAllFirst(i2, i3); cb.addFirst(null); cb.addAllFirst((List) null); cb.addLast(i4); cb.addLast(null); cb.addAllLast(i5); cb.addAllLast((List) null); cb.addFirst(i1); cb.addAllLast(i3, i4, i5); final LinkedList list = cb.build(); Assert.assertNotNull(list); Assert.assertEquals(5, list.size()); Assert.assertSame(i1, list.get(0)); Assert.assertSame(i2, list.get(1)); Assert.assertSame(i3, list.get(2)); Assert.assertSame(i4, list.get(3)); Assert.assertSame(i5, list.get(4)); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/protocol/TestHttpService.java0100644 0000000 0000000 00000064634 12276755421 031424 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.protocol; import java.io.InputStream; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpServerConnection; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.ProtocolException; import org.apache.http.UnsupportedHttpVersionException; import org.apache.http.entity.InputStreamEntity; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestHttpService { @Test public void testInvalidInitialization() throws Exception { final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); try { new HttpService( null, connReuseStrategy, responseFactory, handlerResolver); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } } @Test public void testBasicExecution() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpRequest request = new BasicHttpRequest("GET", "/"); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); Mockito.when(connReuseStrategy.keepAlive(response, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusLine().getStatusCode()); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); Mockito.verify(httprocessor).process(request, context); Mockito.verify(httprocessor).process(response, context); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn).sendResponseEntity(response); Mockito.verify(conn).flush(); Mockito.verify(conn).close(); } @Test public void testBasicExecutionHTTP10() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_0); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); Mockito.when(connReuseStrategy.keepAlive(response, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Mockito.verify(responseFactory).newHttpResponse(HttpVersion.HTTP_1_1, 200, context); } @Test public void testBasicProtocolDowngrade() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpRequest request = new BasicHttpRequest("GET", "/", new HttpVersion(20, 45)); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); Mockito.when(connReuseStrategy.keepAlive(response, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Mockito.verify(responseFactory).newHttpResponse(HttpVersion.HTTP_1_1, 200, context); } @Test public void testExecutionEntityEclosingRequest() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final InputStream instream = Mockito.mock(InputStream.class); final InputStreamEntity entity = new InputStreamEntity(instream, -1); request.setEntity(entity); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); Mockito.when(connReuseStrategy.keepAlive(response, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusLine().getStatusCode()); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); Mockito.verify(conn).receiveRequestEntity(request); Mockito.verify(httprocessor).process(request, context); Mockito.verify(instream).close(); Mockito.verify(httprocessor).process(response, context); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn).sendResponseEntity(response); Mockito.verify(conn).flush(); Mockito.verify(conn).close(); } @Test public void testExecutionEntityEclosingRequestWithExpectContinue() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); final InputStream instream = Mockito.mock(InputStream.class); final InputStreamEntity entity = new InputStreamEntity(instream, -1); request.setEntity(entity); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse resp100 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Continue"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 100, context)).thenReturn(resp100); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); Mockito.when(connReuseStrategy.keepAlive(response, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusLine().getStatusCode()); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); Mockito.verify(conn).sendResponseHeader(resp100); Mockito.verify(conn).receiveRequestEntity(request); Mockito.verify(httprocessor).process(request, context); Mockito.verify(instream).close(); Mockito.verify(httprocessor).process(response, context); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn).sendResponseEntity(response); Mockito.verify(conn, Mockito.times(2)).flush(); Mockito.verify(conn).close(); } @Test public void testExecutionEntityEclosingRequestCustomExpectationVerifier() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() { public void verify( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException { response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); } }; final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver, expectationVerifier); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); final InputStream instream = Mockito.mock(InputStream.class); final InputStreamEntity entity = new InputStreamEntity(instream, -1); request.setEntity(entity); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Continue"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 100, context)).thenReturn(response); Mockito.when(connReuseStrategy.keepAlive(response, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn, Mockito.never()).receiveRequestEntity(request); Mockito.verify(httprocessor).process(response, context); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn).sendResponseEntity(response); Mockito.verify(conn).flush(); Mockito.verify(conn).close(); } @Test public void testExecutionExceptionInCustomExpectationVerifier() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpExpectationVerifier expectationVerifier = Mockito.mock(HttpExpectationVerifier.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver, expectationVerifier); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); final InputStream instream = Mockito.mock(InputStream.class); final InputStreamEntity entity = new InputStreamEntity(instream, -1); request.setEntity(entity); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse resp100 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Continue"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 100, context)).thenReturn(resp100); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, 500, "Oppsie"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, 500, context)).thenReturn(response); Mockito.doThrow(new HttpException("Oopsie")).when(expectationVerifier).verify(request, resp100, context); Mockito.when(connReuseStrategy.keepAlive(response, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode()); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn, Mockito.never()).receiveRequestEntity(request); Mockito.verify(httprocessor).process(response, context); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn).sendResponseEntity(response); Mockito.verify(conn).flush(); Mockito.verify(conn).close(); } @Test public void testMethodNotSupported() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpRequestHandler requestHandler = Mockito.mock(HttpRequestHandler.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpRequest request = new BasicHttpRequest("whatever", "/"); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); final HttpResponse error = new BasicHttpResponse(HttpVersion.HTTP_1_0, 500, "Oppsie"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, 500, context)).thenReturn(error); Mockito.when(handlerResolver.lookup(request)).thenReturn(requestHandler); Mockito.doThrow(new MethodNotSupportedException("whatever")).when( requestHandler).handle(request, response, context); Mockito.when(connReuseStrategy.keepAlive(error, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(error, context.getResponse()); Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, error.getStatusLine().getStatusCode()); Mockito.verify(conn).sendResponseHeader(error); Mockito.verify(httprocessor).process(error, context); Mockito.verify(conn).sendResponseHeader(error); Mockito.verify(conn).sendResponseEntity(error); Mockito.verify(conn).flush(); Mockito.verify(conn).close(); } @Test public void testUnsupportedHttpVersionException() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpRequestHandler requestHandler = Mockito.mock(HttpRequestHandler.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpRequest request = new BasicHttpRequest("whatever", "/"); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); final HttpResponse error = new BasicHttpResponse(HttpVersion.HTTP_1_0, 500, "Oppsie"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, 500, context)).thenReturn(error); Mockito.when(handlerResolver.lookup(request)).thenReturn(requestHandler); Mockito.doThrow(new UnsupportedHttpVersionException()).when( requestHandler).handle(request, response, context); Mockito.when(connReuseStrategy.keepAlive(error, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(error, context.getResponse()); Assert.assertEquals(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, error.getStatusLine().getStatusCode()); Mockito.verify(conn).sendResponseHeader(error); Mockito.verify(httprocessor).process(error, context); Mockito.verify(conn).sendResponseHeader(error); Mockito.verify(conn).sendResponseEntity(error); Mockito.verify(conn).flush(); Mockito.verify(conn).close(); } @Test public void testProtocolException() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpRequestHandler requestHandler = Mockito.mock(HttpRequestHandler.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpRequest request = new BasicHttpRequest("whatever", "/"); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); final HttpResponse error = new BasicHttpResponse(HttpVersion.HTTP_1_0, 500, "Oppsie"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, 500, context)).thenReturn(error); Mockito.when(handlerResolver.lookup(request)).thenReturn(requestHandler); Mockito.doThrow(new ProtocolException("oh, this world is wrong")).when( requestHandler).handle(request, response, context); Mockito.when(connReuseStrategy.keepAlive(error, context)).thenReturn(Boolean.FALSE); httpservice.handleRequest(conn, context); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(error, context.getResponse()); Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, error.getStatusLine().getStatusCode()); Mockito.verify(conn).sendResponseHeader(error); Mockito.verify(httprocessor).process(error, context); Mockito.verify(conn).sendResponseHeader(error); Mockito.verify(conn).sendResponseEntity(error); Mockito.verify(conn).flush(); Mockito.verify(conn).close(); } @Test public void testConnectionKeepAlive() throws Exception { final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class); final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class); final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class); final HttpRequestHandler requestHandler = Mockito.mock(HttpRequestHandler.class); final HttpService httpservice = new HttpService( httprocessor, connReuseStrategy, responseFactory, handlerResolver); final HttpCoreContext context = HttpCoreContext.create(); final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class); final HttpRequest request = new BasicHttpRequest("GET", "/"); Mockito.when(conn.receiveRequestHeader()).thenReturn(request); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, 200, context)).thenReturn(response); Mockito.when(handlerResolver.lookup(request)).thenReturn(requestHandler); Mockito.when(connReuseStrategy.keepAlive(response, context)).thenReturn(Boolean.TRUE); httpservice.handleRequest(conn, context); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); Mockito.verify(httprocessor).process(request, context); Mockito.verify(httprocessor).process(response, context); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn).sendResponseEntity(response); Mockito.verify(conn).flush(); Mockito.verify(conn, Mockito.never()).close(); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/util/0040755 0000000 0000000 00000000000 12276755420 024562 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/util/TestAsserts.java0100644 0000000 0000000 00000004610 12276755420 027707 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import org.junit.Test; /** * Unit tests for {@link Asserts}. */ public class TestAsserts { @Test public void testExpressionCheckPass() { Asserts.check(true, "All is well"); } @Test(expected=IllegalStateException.class) public void testExpressionCheckFail() { Asserts.check(false, "Oopsie"); } @Test(expected=IllegalStateException.class) public void testExpressionNotNullFail() { Asserts.notNull(null, "Stuff"); } @Test(expected=IllegalStateException.class) public void testExpressionNotEmptyFail1() { Asserts.notEmpty((String) null, "Stuff"); } @Test(expected=IllegalStateException.class) public void testExpressionNotEmptyFail2() { Asserts.notEmpty("", "Stuff"); } @Test(expected=IllegalStateException.class) public void testExpressionNotEmptyBlank1() { Asserts.notBlank((String) null, "Stuff"); } @Test(expected=IllegalStateException.class) public void testExpressionNotEmptyBlank2() { Asserts.notBlank("", "Stuff"); } @Test(expected=IllegalStateException.class) public void testExpressionNotBlankFail3() { Asserts.notBlank(" \t \n\r", "Stuff"); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/util/TestArgs.java0100644 0000000 0000000 00000011412 12276755420 027155 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link Args}. */ public class TestArgs { @Test public void testArgCheckPass() { Args.check(true, "All is well"); } @Test(expected=IllegalArgumentException.class) public void testArgCheckFail() { Args.check(false, "Oopsie"); } @Test public void testArgNotNullPass() { final String stuff = "stuff"; Assert.assertSame(stuff, Args.notNull(stuff, "Stuff")); } @Test(expected=IllegalArgumentException.class) public void testArgNotNullFail() { Args.notNull(null, "Stuff"); } @Test public void testArgNotEmptyPass() { final String stuff = "stuff"; Assert.assertSame(stuff, Args.notEmpty(stuff, "Stuff")); } @Test(expected=IllegalArgumentException.class) public void testArgNotEmptyFail1() { Args.notEmpty((String) null, "Stuff"); } @Test(expected=IllegalArgumentException.class) public void testArgNotEmptyFail2() { Args.notEmpty("", "Stuff"); } @Test(expected=IllegalArgumentException.class) public void testArgNotBlankFail1() { Args.notBlank((String) null, "Stuff"); } @Test(expected=IllegalArgumentException.class) public void testArgNotBlankFail2() { Args.notBlank("", "Stuff"); } @Test(expected=IllegalArgumentException.class) public void testArgNotBlankFail3() { Args.notBlank(" \t \n\r", "Stuff"); } @Test public void testArgCollectionNotEmptyPass() { final List list = Arrays.asList("stuff"); Assert.assertSame(list, Args.notEmpty(list, "List")); } @Test(expected=IllegalArgumentException.class) public void testArgCollectionNotEmptyFail1() { Args.notEmpty((List) null, "List"); } @Test(expected=IllegalArgumentException.class) public void testArgCollectionNotEmptyFail2() { Args.notEmpty(Collections.emptyList(), "List"); } @Test public void testPositiveIntPass() { Assert.assertEquals(1, Args.positive(1, "Number")); } @Test(expected=IllegalArgumentException.class) public void testPositiveIntFail1() { Args.positive(-1, "Number"); } @Test(expected=IllegalArgumentException.class) public void testPositiveIntFail2() { Args.positive(0, "Number"); } @Test public void testPositiveLongPass() { Assert.assertEquals(1L, Args.positive(1L, "Number")); } @Test(expected=IllegalArgumentException.class) public void testPositiveLongFail1() { Args.positive(-1L, "Number"); } @Test(expected=IllegalArgumentException.class) public void testPositiveLongFail2() { Args.positive(0L, "Number"); } @Test public void testNotNegativeIntPass1() { Assert.assertEquals(1, Args.notNegative(1, "Number")); } @Test public void testNotNegativeIntPass2() { Assert.assertEquals(0, Args.notNegative(0, "Number")); } @Test(expected=IllegalArgumentException.class) public void testNotNegativeIntFail1() { Args.notNegative(-1, "Number"); } @Test public void testNotNegativeLongPass1() { Assert.assertEquals(1L, Args.notNegative(1L, "Number")); } @Test public void testNotNegativeLongPass2() { Assert.assertEquals(0L, Args.notNegative(0L, "Number")); } @Test(expected=IllegalArgumentException.class) public void testNotNegativeLongFail1() { Args.notNegative(-1L, "Number"); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/util/TestEntityUtils.java0100644 0000000 0000000 00000020605 12276755420 030562 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.message.BasicHeader; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link EntityUtils}. * */ public class TestEntityUtils { @Test public void testNullEntityToByteArray() throws Exception { try { EntityUtils.toByteArray(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testEmptyContentToByteArray() throws Exception { final NullHttpEntity httpentity = new NullHttpEntity(); final byte[] bytes = EntityUtils.toByteArray(httpentity); Assert.assertNull(bytes); } @Test public void testMaxIntContentToByteArray() throws Exception { final byte[] content = "Message content".getBytes("ISO-8859-1"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(content)); httpentity.setContentLength(Integer.MAX_VALUE + 100L); try { EntityUtils.toByteArray(httpentity); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testUnknownLengthContentToByteArray() throws Exception { final byte[] bytes = "Message content".getBytes("ISO-8859-1"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(bytes)); httpentity.setContentLength(-1L); final byte[] bytes2 = EntityUtils.toByteArray(httpentity); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } } @Test public void testKnownLengthContentToByteArray() throws Exception { final byte[] bytes = "Message content".getBytes("ISO-8859-1"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(bytes)); httpentity.setContentLength(bytes.length); final byte[] bytes2 = EntityUtils.toByteArray(httpentity); Assert.assertNotNull(bytes2); Assert.assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { Assert.assertEquals(bytes[i], bytes2[i]); } } @Test public void testNullEntityToString() throws Exception { try { EntityUtils.toString(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testEmptyContentToString() throws Exception { final NullHttpEntity httpentity = new NullHttpEntity(); final String s = EntityUtils.toString(httpentity); Assert.assertNull(s); } @Test public void testMaxIntContentToString() throws Exception { final byte[] content = "Message content".getBytes("ISO-8859-1"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(content)); httpentity.setContentLength(Integer.MAX_VALUE + 100L); try { EntityUtils.toString(httpentity); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testUnknownLengthContentToString() throws Exception { final byte[] bytes = "Message content".getBytes("ISO-8859-1"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(bytes)); httpentity.setContentLength(-1L); final String s = EntityUtils.toString(httpentity, "ISO-8859-1"); Assert.assertEquals("Message content", s); } @Test public void testKnownLengthContentToString() throws Exception { final byte[] bytes = "Message content".getBytes("ISO-8859-1"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(bytes)); httpentity.setContentLength(bytes.length); final String s = EntityUtils.toString(httpentity, "ISO-8859-1"); Assert.assertEquals("Message content", s); } static final int SWISS_GERMAN_HELLO [] = { 0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4 }; static final int RUSSIAN_HELLO [] = { 0x412, 0x441, 0x435, 0x43C, 0x5F, 0x43F, 0x440, 0x438, 0x432, 0x435, 0x442 }; private static String constructString(final int [] unicodeChars) { final StringBuilder buffer = new StringBuilder(); if (unicodeChars != null) { for (final int unicodeChar : unicodeChars) { buffer.append((char)unicodeChar); } } return buffer.toString(); } @Test public void testNoCharsetContentToString() throws Exception { final String content = constructString(SWISS_GERMAN_HELLO); final byte[] bytes = content.getBytes("ISO-8859-1"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(bytes)); httpentity.setContentType(new BasicHeader("Content-Type", "text/plain")); final String s = EntityUtils.toString(httpentity); Assert.assertEquals(content, s); } @Test public void testDefaultCharsetContentToString() throws Exception { final String content = constructString(RUSSIAN_HELLO); final byte[] bytes = content.getBytes("KOI8-R"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(bytes)); httpentity.setContentType(new BasicHeader("Content-Type", "text/plain")); final String s = EntityUtils.toString(httpentity, "KOI8-R"); Assert.assertEquals(content, s); } @Test public void testContentWithContentTypeToString() throws Exception { final String content = constructString(RUSSIAN_HELLO); final byte[] bytes = content.getBytes("UTF-8"); final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContent(new ByteArrayInputStream(bytes)); httpentity.setContentType(new BasicHeader("Content-Type", "text/plain; charset=UTF-8")); final String s = EntityUtils.toString(httpentity, "ISO-8859-1"); Assert.assertEquals(content, s); } /** * Helper class that returns null as the content. */ public static class NullHttpEntity extends BasicHttpEntity { // default constructor /** * Obtains no content. * This method disables the state checks in the base class. * * @return null */ @Override public InputStream getContent() { return null; } } // class NullEntity } // class TestEntityUtils httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/util/TestEncodingUtils.java0100644 0000000 0000000 00000014707 12276755420 031042 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link TestEncodingUtils}. * */ public class TestEncodingUtils { private static String constructString(final int [] unicodeChars) { final StringBuilder buffer = new StringBuilder(); if (unicodeChars != null) { for (final int unicodeChar : unicodeChars) { buffer.append((char)unicodeChar); } } return buffer.toString(); } static final int SWISS_GERMAN_HELLO [] = { 0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4 }; @Test public void testBytesToString() throws Exception { final String s = constructString(SWISS_GERMAN_HELLO); final byte[] utf = s.getBytes("UTF-8"); final byte[] latin1 = s.getBytes("ISO-8859-1"); final String s1 = EncodingUtils.getString(utf, "UTF-8"); final String s2 = EncodingUtils.getString(latin1, "ISO-8859-1"); Assert.assertEquals(s, s1); Assert.assertEquals(s, s2); try { EncodingUtils.getString(null, 0, 0, "UTF-8"); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { EncodingUtils.getString(null, "UTF-8"); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { EncodingUtils.getString(new byte[] {}, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { EncodingUtils.getString(new byte[] {}, ""); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testStringToBytesToString() throws Exception { final String s = constructString(SWISS_GERMAN_HELLO); final byte[] utf = s.getBytes("UTF-8"); final byte[] latin1 = s.getBytes("ISO-8859-1"); final byte[] data1 = EncodingUtils.getBytes(s, "UTF-8"); final byte[] data2 = EncodingUtils.getBytes(s, "ISO-8859-1"); Assert.assertNotNull(data1); Assert.assertEquals(utf.length, data1.length); for (int i = 0; i < utf.length; i++) { Assert.assertEquals(utf[i], data1[i]); } Assert.assertNotNull(data2); Assert.assertEquals(latin1.length, data2.length); for (int i = 0; i < latin1.length; i++) { Assert.assertEquals(latin1[i], data2[i]); } try { EncodingUtils.getBytes(null, "UTF-8"); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { EncodingUtils.getBytes("what not", null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { EncodingUtils.getBytes("what not", ""); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testAsciiBytesToString() throws Exception { final String s = "ascii only, I mean it!"; Assert.assertEquals(s, EncodingUtils.getAsciiString(s.getBytes("US-ASCII"))); try { EncodingUtils.getAsciiString(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { EncodingUtils.getAsciiString(null, 0, 0); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testAsciiStringToBytes() throws Exception { final String s = "ascii only, I mean it!"; final byte[] ascii = s.getBytes("US-ASCII"); final byte[] data = EncodingUtils.getAsciiBytes(s); Assert.assertNotNull(data); Assert.assertEquals(ascii.length, data.length); for (int i = 0; i < ascii.length; i++) { Assert.assertEquals(ascii[i], data[i]); } try { EncodingUtils.getAsciiBytes(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testUnsupportedEncoding() { final String s = constructString(SWISS_GERMAN_HELLO); final byte[] b1 = s.getBytes(); final byte[] b2 = EncodingUtils.getBytes(s, "ThisJustAintRight"); Assert.assertEquals(b1.length, b2.length); for (int i = 0; i < b1.length; i++) { Assert.assertEquals(b1[i], b2[i]); } final String s1 = new String(b1); final String s2 = EncodingUtils.getString(b1, "ThisJustAintRight"); Assert.assertEquals(s1, s2); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/util/TestLangUtils.java0100644 0000000 0000000 00000006437 12276755420 030176 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link LangUtils}. * */ public class TestLangUtils { @Test public void testBasicHash() { final Integer i = new Integer(1234); final int h1 = LangUtils.hashCode(LangUtils.HASH_SEED, i.hashCode()); final int h2 = LangUtils.hashCode(LangUtils.HASH_SEED, i); Assert.assertTrue(h1 == h2); } @Test public void testNullObjectHash() { final int h1 = LangUtils.hashCode(LangUtils.HASH_SEED, null); final int h2 = LangUtils.hashCode(LangUtils.HASH_SEED, 0); Assert.assertTrue(h1 == h2); } @Test public void testBooleanHash() { final int h1 = LangUtils.hashCode(LangUtils.HASH_SEED, true); final int h2 = LangUtils.hashCode(LangUtils.HASH_SEED, false); final int h3 = LangUtils.hashCode(LangUtils.HASH_SEED, true); final int h4 = LangUtils.hashCode(LangUtils.HASH_SEED, false); Assert.assertTrue(h1 != h2); Assert.assertTrue(h1 == h3); Assert.assertTrue(h2 == h4); } @Test public void testBasicEquality() { Assert.assertTrue(LangUtils.equals(null, null)); Assert.assertFalse(LangUtils.equals(null, "abc")); Assert.assertFalse(LangUtils.equals("abc", null)); Assert.assertTrue(LangUtils.equals("abc", "abc")); } @Test public void testArrayEquals() { Assert.assertFalse(LangUtils.equals(null, new Object[] {})); Assert.assertFalse(LangUtils.equals(new Object[] {}, null)); Assert.assertTrue(LangUtils.equals(new Object[] {}, new Object[] {})); Assert.assertFalse(LangUtils.equals( new Object[] {new Integer(1), new Integer(2)}, new Object[] {new Integer(1)})); Assert.assertFalse(LangUtils.equals( new Object[] {new Integer(1), new Integer(2)}, new Object[] {new Integer(1), new Integer(3)})); Assert.assertTrue(LangUtils.equals( new Object[] {new Integer(1), new Integer(2)}, new Object[] {new Integer(1), new Integer(2)})); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/util/TestByteArrayBuffer.java0100644 0000000 0000000 00000026077 12276755420 031332 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link ByteArrayBuffer}. * */ public class TestByteArrayBuffer { @Test public void testConstructor() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(16); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(0, buffer.length()); Assert.assertNotNull(buffer.buffer()); Assert.assertEquals(16, buffer.buffer().length); try { new ByteArrayBuffer(-1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testSimpleAppend() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(16); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(0, buffer.length()); final byte[] b1 = buffer.toByteArray(); Assert.assertNotNull(b1); Assert.assertEquals(0, b1.length); Assert.assertTrue(buffer.isEmpty()); Assert.assertFalse(buffer.isFull()); final byte[] tmp = new byte[] { 1, 2, 3, 4}; buffer.append(tmp, 0, tmp.length); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(4, buffer.length()); Assert.assertFalse(buffer.isEmpty()); Assert.assertFalse(buffer.isFull()); final byte[] b2 = buffer.toByteArray(); Assert.assertNotNull(b2); Assert.assertEquals(4, b2.length); for (int i = 0; i < tmp.length; i++) { Assert.assertEquals(tmp[i], b2[i]); Assert.assertEquals(tmp[i], buffer.byteAt(i)); } buffer.clear(); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(0, buffer.length()); Assert.assertTrue(buffer.isEmpty()); Assert.assertFalse(buffer.isFull()); } @Test public void testExpandAppend() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(4); Assert.assertEquals(4, buffer.capacity()); final byte[] tmp = new byte[] { 1, 2, 3, 4}; buffer.append(tmp, 0, 2); buffer.append(tmp, 0, 4); buffer.append(tmp, 0, 0); Assert.assertEquals(8, buffer.capacity()); Assert.assertEquals(6, buffer.length()); buffer.append(tmp, 0, 4); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(10, buffer.length()); } @Test public void testInvalidAppend() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(4); buffer.append((byte[])null, 0, 0); final byte[] tmp = new byte[] { 1, 2, 3, 4}; try { buffer.append(tmp, -1, 0); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 0, -1); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 0, 8); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 10, Integer.MAX_VALUE); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 2, 4); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } } @Test public void testAppendOneByte() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(4); Assert.assertEquals(4, buffer.capacity()); final byte[] tmp = new byte[] { 1, 127, -1, -128, 1, -2}; for (final byte element : tmp) { buffer.append(element); } Assert.assertEquals(8, buffer.capacity()); Assert.assertEquals(6, buffer.length()); for (int i = 0; i < tmp.length; i++) { Assert.assertEquals(tmp[i], buffer.byteAt(i)); } } @Test public void testSetLength() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(4); buffer.setLength(2); Assert.assertEquals(2, buffer.length()); } @Test public void testSetInvalidLength() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(4); try { buffer.setLength(-2); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.setLength(200); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } } @Test public void testEnsureCapacity() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(4); buffer.ensureCapacity(2); Assert.assertEquals(4, buffer.capacity()); buffer.ensureCapacity(8); Assert.assertEquals(8, buffer.capacity()); } @Test public void testIndexOf() throws Exception { final byte COLON = (byte) ':'; final byte COMMA = (byte) ','; final byte[] bytes = "name1: value1; name2: value2".getBytes("US-ASCII"); final int index1 = 5; final int index2 = 20; final ByteArrayBuffer buffer = new ByteArrayBuffer(16); buffer.append(bytes, 0, bytes.length); Assert.assertEquals(index1, buffer.indexOf(COLON)); Assert.assertEquals(-1, buffer.indexOf(COMMA)); Assert.assertEquals(index1, buffer.indexOf(COLON, -1, 11)); Assert.assertEquals(index1, buffer.indexOf(COLON, 0, 1000)); Assert.assertEquals(-1, buffer.indexOf(COLON, 2, 1)); Assert.assertEquals(index2, buffer.indexOf(COLON, index1 + 1, buffer.length())); } @Test public void testAppendCharArrayAsAscii() throws Exception { final String s1 = "stuff"; final String s2 = " and more stuff"; final char[] b1 = s1.toCharArray(); final char[] b2 = s2.toCharArray(); final ByteArrayBuffer buffer = new ByteArrayBuffer(8); buffer.append(b1, 0, b1.length); buffer.append(b2, 0, b2.length); Assert.assertEquals(s1 + s2, new String(buffer.toByteArray(), "US-ASCII")); } @Test public void testAppendNullCharArray() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(8); buffer.append((char[])null, 0, 0); Assert.assertEquals(0, buffer.length()); } @Test public void testAppendEmptyCharArray() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(8); buffer.append(new char[] {}, 0, 0); Assert.assertEquals(0, buffer.length()); } @Test public void testAppendNullCharArrayBuffer() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(8); buffer.append((CharArrayBuffer)null, 0, 0); Assert.assertEquals(0, buffer.length()); } @Test public void testInvalidAppendCharArrayAsAscii() throws Exception { final ByteArrayBuffer buffer = new ByteArrayBuffer(4); buffer.append((char[])null, 0, 0); final char[] tmp = new char[] { '1', '2', '3', '4'}; try { buffer.append(tmp, -1, 0); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 0, -1); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 0, 8); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 10, Integer.MAX_VALUE); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 2, 4); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } } @Test public void testSerialization() throws Exception { final ByteArrayBuffer orig = new ByteArrayBuffer(32); orig.append(1); orig.append(2); orig.append(3); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final ByteArrayBuffer clone = (ByteArrayBuffer) instream.readObject(); Assert.assertEquals(orig.capacity(), clone.capacity()); Assert.assertEquals(orig.length(), clone.length()); final byte[] data = clone.toByteArray(); Assert.assertNotNull(data); Assert.assertEquals(3, data.length); Assert.assertEquals(1, data[0]); Assert.assertEquals(2, data[1]); Assert.assertEquals(3, data[2]); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/util/TestCharArrayBuffer.java0100644 0000000 0000000 00000034347 12276755420 031303 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link CharArrayBuffer}. * */ public class TestCharArrayBuffer { @Test public void testConstructor() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(16); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(0, buffer.length()); Assert.assertNotNull(buffer.buffer()); Assert.assertEquals(16, buffer.buffer().length); try { new CharArrayBuffer(-1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testSimpleAppend() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(16); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(0, buffer.length()); final char[] b1 = buffer.toCharArray(); Assert.assertNotNull(b1); Assert.assertEquals(0, b1.length); Assert.assertTrue(buffer.isEmpty()); Assert.assertFalse(buffer.isFull()); final char[] tmp = new char[] { '1', '2', '3', '4'}; buffer.append(tmp, 0, tmp.length); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(4, buffer.length()); Assert.assertFalse(buffer.isEmpty()); Assert.assertFalse(buffer.isFull()); final char[] b2 = buffer.toCharArray(); Assert.assertNotNull(b2); Assert.assertEquals(4, b2.length); for (int i = 0; i < tmp.length; i++) { Assert.assertEquals(tmp[i], b2[i]); Assert.assertEquals(tmp[i], buffer.charAt(i)); } Assert.assertEquals("1234", buffer.toString()); buffer.clear(); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(0, buffer.length()); Assert.assertTrue(buffer.isEmpty()); Assert.assertFalse(buffer.isFull()); } @Test public void testExpandAppend() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(4); Assert.assertEquals(4, buffer.capacity()); final char[] tmp = new char[] { '1', '2', '3', '4'}; buffer.append(tmp, 0, 2); buffer.append(tmp, 0, 4); buffer.append(tmp, 0, 0); Assert.assertEquals(8, buffer.capacity()); Assert.assertEquals(6, buffer.length()); buffer.append(tmp, 0, 4); Assert.assertEquals(16, buffer.capacity()); Assert.assertEquals(10, buffer.length()); Assert.assertEquals("1212341234", buffer.toString()); } @Test public void testAppendString() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(8); buffer.append("stuff"); buffer.append(" and more stuff"); Assert.assertEquals("stuff and more stuff", buffer.toString()); } @Test public void testAppendNullString() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(8); buffer.append((String)null); Assert.assertEquals("null", buffer.toString()); } @Test public void testAppendCharArrayBuffer() throws Exception { final CharArrayBuffer buffer1 = new CharArrayBuffer(8); buffer1.append(" and more stuff"); final CharArrayBuffer buffer2 = new CharArrayBuffer(8); buffer2.append("stuff"); buffer2.append(buffer1); Assert.assertEquals("stuff and more stuff", buffer2.toString()); } @Test public void testAppendNullCharArrayBuffer() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(8); buffer.append((CharArrayBuffer)null); buffer.append((CharArrayBuffer)null, 0, 0); Assert.assertEquals("", buffer.toString()); } @Test public void testAppendSingleChar() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(4); buffer.append('1'); buffer.append('2'); buffer.append('3'); buffer.append('4'); buffer.append('5'); buffer.append('6'); Assert.assertEquals("123456", buffer.toString()); } @Test public void testInvalidCharArrayAppend() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(4); buffer.append((char[])null, 0, 0); final char[] tmp = new char[] { '1', '2', '3', '4'}; try { buffer.append(tmp, -1, 0); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 0, -1); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 0, 8); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 10, Integer.MAX_VALUE); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 2, 4); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } } @Test public void testSetLength() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(4); buffer.setLength(2); Assert.assertEquals(2, buffer.length()); } @Test public void testSetInvalidLength() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(4); try { buffer.setLength(-2); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.setLength(200); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } } @Test public void testEnsureCapacity() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(4); buffer.ensureCapacity(2); Assert.assertEquals(4, buffer.capacity()); buffer.ensureCapacity(8); Assert.assertEquals(8, buffer.capacity()); } @Test public void testIndexOf() { final CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append("name: value"); Assert.assertEquals(4, buffer.indexOf(':')); Assert.assertEquals(-1, buffer.indexOf(',')); Assert.assertEquals(4, buffer.indexOf(':', -1, 11)); Assert.assertEquals(4, buffer.indexOf(':', 0, 1000)); Assert.assertEquals(-1, buffer.indexOf(':', 2, 1)); } @Test public void testSubstring() { final CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append(" name: value "); Assert.assertEquals(5, buffer.indexOf(':')); Assert.assertEquals(" name", buffer.substring(0, 5)); Assert.assertEquals(" value ", buffer.substring(6, buffer.length())); Assert.assertEquals("name", buffer.substringTrimmed(0, 5)); Assert.assertEquals("value", buffer.substringTrimmed(6, buffer.length())); Assert.assertEquals("", buffer.substringTrimmed(13, buffer.length())); } @Test public void testSubstringIndexOfOutBound() { final CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append("stuff"); try { buffer.substring(-2, 10); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.substringTrimmed(-2, 10); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.substring(12, 10); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.substringTrimmed(12, 10); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.substring(2, 1); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.substringTrimmed(2, 1); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } } @Test public void testAppendAsciiByteArray() throws Exception { final String s1 = "stuff"; final String s2 = " and more stuff"; final byte[] b1 = s1.getBytes("US-ASCII"); final byte[] b2 = s2.getBytes("US-ASCII"); final CharArrayBuffer buffer = new CharArrayBuffer(8); buffer.append(b1, 0, b1.length); buffer.append(b2, 0, b2.length); Assert.assertEquals("stuff and more stuff", buffer.toString()); } @Test public void testAppendISOByteArray() throws Exception { final byte[] b = new byte[] {0x00, 0x20, 0x7F, -0x80, -0x01}; final CharArrayBuffer buffer = new CharArrayBuffer(8); buffer.append(b, 0, b.length); final char[] ch = buffer.toCharArray(); Assert.assertNotNull(ch); Assert.assertEquals(5, ch.length); Assert.assertEquals(0x00, ch[0]); Assert.assertEquals(0x20, ch[1]); Assert.assertEquals(0x7F, ch[2]); Assert.assertEquals(0x80, ch[3]); Assert.assertEquals(0xFF, ch[4]); } @Test public void testAppendNullByteArray() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(8); buffer.append((byte[])null, 0, 0); Assert.assertEquals("", buffer.toString()); } @Test public void testAppendNullByteArrayBuffer() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(8); buffer.append((ByteArrayBuffer)null, 0, 0); Assert.assertEquals("", buffer.toString()); } @Test public void testInvalidAppendAsciiByteArray() throws Exception { final CharArrayBuffer buffer = new CharArrayBuffer(4); buffer.append((byte[])null, 0, 0); final byte[] tmp = new byte[] { '1', '2', '3', '4'}; try { buffer.append(tmp, -1, 0); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 0, -1); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 0, 8); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 10, Integer.MAX_VALUE); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.append(tmp, 2, 4); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } } @Test public void testSerialization() throws Exception { final CharArrayBuffer orig = new CharArrayBuffer(32); orig.append('a'); orig.append('b'); orig.append('c'); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final CharArrayBuffer clone = (CharArrayBuffer) instream.readObject(); Assert.assertEquals(orig.capacity(), clone.capacity()); Assert.assertEquals(orig.length(), clone.length()); final char[] data = clone.toCharArray(); Assert.assertNotNull(data); Assert.assertEquals(3, data.length); Assert.assertEquals('a', data[0]); Assert.assertEquals('b', data[1]); Assert.assertEquals('c', data[2]); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/0040755 0000000 0000000 00000000000 12276755422 026015 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/Wire.java0100644 0000000 0000000 00000006121 12276755422 027563 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.testserver; import org.apache.commons.logging.Log; class Wire { private final Log log; private final String id; public Wire(final Log log, final String id) { super(); this.log = log; this.id = id; } private void wire(final String header, final byte[] b, final int pos, final int off) { final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < off; i++) { final int ch = b[pos + i]; if (ch == 13) { buffer.append("[\\r]"); } else if (ch == 10) { buffer.append("[\\n]\""); buffer.insert(0, "\""); buffer.insert(0, header); this.log.debug(this.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); this.log.debug(this.id + " " + buffer.toString()); } } public boolean isEnabled() { return this.log.isDebugEnabled(); } public void output(final byte[] b, final int pos, final int off) { wire("<< ", b, pos, off); } public void input(final byte[] b, final int pos, final int off) { wire(">> ", b, pos, off); } public void output(final byte[] b) { output(b, 0, b.length); } public void input(final byte[] b) { input(b, 0, b.length); } public void output(final int b) { output(new byte[] {(byte) b}); } public void input(final int b) { input(new byte[] {(byte) b}); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/HttpServer.java0100644 0000000 0000000 00000016143 12276755422 030770 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.testserver; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpException; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpServerConnection; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.UriHttpRequestHandlerMapper; import org.apache.http.util.Asserts; public class HttpServer { private final HttpProcessor httpproc; private final ConnectionReuseStrategy connStrategy; private final HttpResponseFactory responseFactory; private final UriHttpRequestHandlerMapper reqistry; private final ServerSocket serversocket; private volatile HttpExpectationVerifier expectationVerifier; private volatile Thread listener; private volatile boolean shutdown; private volatile int timeout; public HttpServer() throws IOException { super(); this.httpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer("TEST-SERVER/1.1"), new ResponseContent(), new ResponseConnControl() }); this.connStrategy = DefaultConnectionReuseStrategy.INSTANCE; this.responseFactory = DefaultHttpResponseFactory.INSTANCE; this.reqistry = new UriHttpRequestHandlerMapper(); this.serversocket = new ServerSocket(0); } public int getTimeout() { return this.timeout; } public void setTimeout(final int timeout) { this.timeout = timeout; } public void registerHandler( final String pattern, final HttpRequestHandler handler) { this.reqistry.register(pattern, handler); } public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; } private HttpServerConnection acceptConnection() throws IOException { final Socket socket = this.serversocket.accept(); final LoggingBHttpServerConnection conn = new LoggingBHttpServerConnection(8 * 1024); conn.bind(socket); conn.setSocketTimeout(this.timeout); return conn; } public int getPort() { return this.serversocket.getLocalPort(); } public InetAddress getInetAddress() { return this.serversocket.getInetAddress(); } public void start() { Asserts.check(this.listener == null, "Listener already running"); this.listener = new Thread(new Runnable() { public void run() { while (!shutdown && !Thread.interrupted()) { try { // Set up HTTP connection final HttpServerConnection conn = acceptConnection(); // Set up the HTTP service final HttpService httpService = new HttpService( httpproc, connStrategy, responseFactory, reqistry, expectationVerifier); // Start worker thread final Thread t = new WorkerThread(httpService, conn); t.setDaemon(true); t.start(); } catch (final InterruptedIOException ex) { break; } catch (final IOException e) { break; } } } }); this.listener.start(); } public void shutdown() { if (this.shutdown) { return; } this.shutdown = true; try { this.serversocket.close(); } catch (final IOException ignore) {} this.listener.interrupt(); try { this.listener.join(1000); } catch (final InterruptedException ignore) {} } static class WorkerThread extends Thread { private final HttpService httpservice; private final HttpServerConnection conn; public WorkerThread( final HttpService httpservice, final HttpServerConnection conn) { super(); this.httpservice = httpservice; this.conn = conn; } @Override public void run() { final HttpContext context = new BasicHttpContext(null); try { while (!Thread.interrupted() && this.conn.isOpen()) { this.httpservice.handleRequest(this.conn, context); } } catch (final ConnectionClosedException ex) { } catch (final IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } catch (final HttpException ex) { System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage()); } finally { try { this.conn.shutdown(); } catch (final IOException ignore) {} } } } } ././@LongLink0100644 0000000 0000000 00000000156 12276757361 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/LoggingBHttpClientConnection.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/LoggingBHttpClientConnec0100644 0000000 0000000 00000012210 12276755422 032546 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.testserver; 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.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.DefaultBHttpClientConnection; import org.apache.http.io.HttpMessageParserFactory; import org.apache.http.io.HttpMessageWriterFactory; public class LoggingBHttpClientConnection extends DefaultBHttpClientConnection { private static final AtomicLong COUNT = new AtomicLong(); private final String id; private final Log log; private final Log headerlog; private final Wire wire; public LoggingBHttpClientConnection( 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 = "http-outgoing-" + COUNT.incrementAndGet(); this.log = LogFactory.getLog(getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); this.wire = new Wire(LogFactory.getLog("org.apache.http.wire"), this.id); } public LoggingBHttpClientConnection(final int buffersize) { this(buffersize, buffersize, null, null, null, null, null, null, null); } @Override public void close() throws IOException { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": Close connection"); } super.close(); } @Override public void shutdown() throws IOException { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": Shutdown connection"); } super.shutdown(); } @Override protected InputStream getSocketInputStream(final Socket socket) throws IOException { InputStream in = super.getSocketInputStream(socket); if (wire.isEnabled()) { in = new LoggingInputStream(in, wire); } return in; } @Override protected OutputStream getSocketOutputStream(final Socket socket) throws IOException { OutputStream out = super.getSocketOutputStream(socket); if (wire.isEnabled()) { out = new LoggingOutputStream(out, wire); } return out; } @Override protected void onResponseReceived(final HttpResponse response) { if (response != null && this.headerlog.isDebugEnabled()) { this.headerlog.debug(this.id + " << " + response.getStatusLine().toString()); final Header[] headers = response.getAllHeaders(); for (final Header header : headers) { this.headerlog.debug(this.id + " << " + header.toString()); } } } @Override protected void onRequestSubmitted(final HttpRequest request) { if (request != null && this.headerlog.isDebugEnabled()) { this.headerlog.debug(id + " >> " + request.getRequestLine().toString()); final Header[] headers = request.getAllHeaders(); for (final Header header : headers) { this.headerlog.debug(this.id + " >> " + header.toString()); } } } } ././@LongLink0100644 0000000 0000000 00000000145 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/LoggingOutputStream.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/LoggingOutputStream.java0100644 0000000 0000000 00000004113 12276755422 032637 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.testserver; import java.io.IOException; import java.io.OutputStream; 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 { wire.output(b); } @Override public void write(final byte[] b) throws IOException { wire.output(b); out.write(b); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { wire.output(b, off, len); out.write(b, off, len); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/HttpClient.java0100644 0000000 0000000 00000010627 12276755422 030741 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.testserver; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpClientConnection; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.impl.DefaultBHttpClientConnection; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; public class HttpClient { private final HttpProcessor httpproc; private final HttpRequestExecutor httpexecutor; private final ConnectionReuseStrategy connStrategy; private final HttpCoreContext context; private volatile int timeout; public HttpClient(final HttpProcessor httpproc) { super(); this.httpproc = httpproc; this.connStrategy = DefaultConnectionReuseStrategy.INSTANCE; this.httpexecutor = new HttpRequestExecutor(); this.context = new HttpCoreContext(); } public HttpClient() { this(new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent("TEST-CLIENT/1.1"), new RequestExpectContinue(true) })); } public HttpContext getContext() { return this.context; } public int getTimeout() { return this.timeout; } public void setTimeout(final int timeout) { this.timeout = timeout; } public DefaultBHttpClientConnection createConnection() { return new LoggingBHttpClientConnection(8 * 1024); } public void connect(final HttpHost host, final DefaultBHttpClientConnection conn) throws IOException { final Socket socket = new Socket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), this.timeout); conn.bind(socket); conn.setSocketTimeout(this.timeout); } public HttpResponse execute( final HttpRequest request, final HttpHost targetHost, final HttpClientConnection conn) throws HttpException, IOException { this.context.setTargetHost(targetHost); this.httpexecutor.preProcess(request, this.httpproc, this.context); final HttpResponse response = this.httpexecutor.execute(request, conn, this.context); this.httpexecutor.postProcess(response, this.httpproc, this.context); return response; } public boolean keepAlive(final HttpResponse response) { return this.connStrategy.keepAlive(response, this.context); } } ././@LongLink0100644 0000000 0000000 00000000156 12276757361 011655 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/LoggingBHttpServerConnection.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/LoggingBHttpServerConnec0100644 0000000 0000000 00000012215 12276755422 032603 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.testserver; 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.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.DefaultBHttpServerConnection; import org.apache.http.io.HttpMessageParserFactory; import org.apache.http.io.HttpMessageWriterFactory; public class LoggingBHttpServerConnection extends DefaultBHttpServerConnection { private static final AtomicLong COUNT = new AtomicLong(); private final String id; private final Log log; private final Log headerlog; private final Wire wire; public LoggingBHttpServerConnection( 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, outgoingContentStrategy, requestParserFactory, responseWriterFactory); this.id = "http-incoming-" + COUNT.incrementAndGet(); this.log = LogFactory.getLog(getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); this.wire = new Wire(LogFactory.getLog("org.apache.http.wire"), this.id); } public LoggingBHttpServerConnection(final int buffersize) { this(buffersize, buffersize, null, null, null, null, null, null, null); } @Override public void close() throws IOException { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": Close connection"); } super.close(); } @Override public void shutdown() throws IOException { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": Shutdown connection"); } super.shutdown(); } @Override protected InputStream getSocketInputStream(final Socket socket) throws IOException { InputStream in = super.getSocketInputStream(socket); if (wire.isEnabled()) { in = new LoggingInputStream(in, wire); } return in; } @Override protected OutputStream getSocketOutputStream(final Socket socket) throws IOException { OutputStream out = super.getSocketOutputStream(socket); if (wire.isEnabled()) { out = new LoggingOutputStream(out, wire); } return out; } @Override protected void onRequestReceived(final HttpRequest request) { if (request != null && this.headerlog.isDebugEnabled()) { this.headerlog.debug(this.id + " >> " + request.getRequestLine().toString()); final Header[] headers = request.getAllHeaders(); for (final Header header : headers) { this.headerlog.debug(this.id + " >> " + header.toString()); } } } @Override protected void onResponseSubmitted(final HttpResponse response) { if (response != null && this.headerlog.isDebugEnabled()) { this.headerlog.debug(this.id + " << " + response.getStatusLine().toString()); final Header[] headers = response.getAllHeaders(); for (final Header header : headers) { this.headerlog.debug(this.id + " << " + header.toString()); } } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/testserver/LoggingInputStream.java0100644 0000000 0000000 00000005351 12276755422 032443 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.testserver; import java.io.IOException; import java.io.InputStream; 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 { final int b = in.read(); if (b != -1) { wire.input(b); } return b; } @Override public int read(final byte[] b) throws IOException { final int bytesRead = in.read(b); if (bytesRead != -1) { wire.input(b, 0, bytesRead); } return bytesRead; } @Override public int read(final byte[] b, final int off, final int len) throws IOException { final int bytesRead = in.read(b, off, len); if (bytesRead != -1) { wire.input(b, off, bytesRead); } return bytesRead; } @Override public long skip(final long n) throws IOException { return super.skip(n); } @Override public int available() throws IOException { return in.available(); } @Override public synchronized void mark(final int readlimit) { super.mark(readlimit); } @Override public synchronized void reset() throws IOException { super.reset(); } @Override public boolean markSupported() { return false; } @Override public void close() throws IOException { in.close(); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/pool/0040755 0000000 0000000 00000000000 12276755417 024564 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/pool/TestConnPool.java0100644 0000000 0000000 00000074756 12276755417 030036 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.pool; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.http.HttpConnection; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestConnPool { private static final int GRACE_PERIOD = 10000; static interface LocalConnFactory extends ConnFactory { } static class LocalPoolEntry extends PoolEntry { private boolean closed; public LocalPoolEntry(final String route, final HttpConnection conn) { super(null, route, conn); } @Override public void close() { if (this.closed) { return; } this.closed = true; try { getConnection().close(); } catch (final IOException ignore) { } } @Override public boolean isClosed() { return this.closed; } } static class LocalConnPool extends AbstractConnPool { public LocalConnPool( final ConnFactory connFactory, final int defaultMaxPerRoute, final int maxTotal) { super(connFactory, defaultMaxPerRoute, maxTotal); } @Override protected LocalPoolEntry createEntry(final String route, final HttpConnection conn) { return new LocalPoolEntry(route, conn); } } @Test public void testEmptyPool() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); pool.setDefaultMaxPerRoute(5); pool.setMaxPerRoute("somehost", 3); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(10, totals.getMax()); final PoolStats stats = pool.getStats("somehost"); Assert.assertEquals(0, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); Assert.assertEquals(3, stats.getMax()); Assert.assertEquals("[leased: []][available: []][pending: []]", pool.toString()); } @Test public void testInvalidConstruction() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); try { new LocalConnPool(connFactory, -1, 1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { new LocalConnPool(connFactory, 1, -1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } } @Test public void testLeaseRelease() throws Exception { final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); Mockito.when(conn2.isOpen()).thenReturn(true); final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1); Mockito.when(connFactory.create(Mockito.eq("otherhost"))).thenReturn(conn2); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); final Future future1 = pool.lease("somehost", null); final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry1); final Future future2 = pool.lease("somehost", null); final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry2); final Future future3 = pool.lease("otherhost", null); final LocalPoolEntry entry3 = future3.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry3); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(3, totals.getLeased()); final LocalPoolEntry entry = future1.get(); Assert.assertSame(entry1, entry); pool.release(entry1, true); pool.release(entry2, true); pool.release(entry3, false); Mockito.verify(conn1, Mockito.never()).close(); Mockito.verify(conn2, Mockito.times(1)).close(); totals = pool.getTotalStats(); Assert.assertEquals(2, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); } @Test public void testLeaseIllegal() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); try { pool.lease(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } } @Test public void testReleaseUnknownEntry() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); pool.release(new LocalPoolEntry("somehost", Mockito.mock(HttpConnection.class)), true); } static class GetPoolEntryThread extends Thread { private final Future future; private final long time; private final TimeUnit tunit; private volatile LocalPoolEntry entry; private volatile Exception ex; GetPoolEntryThread(final Future future, final long time, final TimeUnit tunit) { super(); this.future = future; this.time = time; this.tunit = tunit; setDaemon(true); } GetPoolEntryThread(final Future future) { this(future, 1000, TimeUnit.SECONDS); } @Override public void run() { try { this.entry = this.future.get(this.time, this.tunit); } catch (final Exception ex) { this.ex = ex; } } public boolean isDone() { return this.future.isDone(); } public LocalPoolEntry getEntry() { return this.entry; } public Exception getException() { return this.ex; } } @Test public void testMaxLimits() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); Mockito.when(conn2.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("otherhost"))).thenReturn(conn2); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); pool.setMaxPerRoute("somehost", 2); pool.setMaxPerRoute("otherhost", 1); pool.setMaxTotal(3); final Future future1 = pool.lease("somehost", null); final GetPoolEntryThread t1 = new GetPoolEntryThread(future1); t1.start(); final Future future2 = pool.lease("somehost", null); final GetPoolEntryThread t2 = new GetPoolEntryThread(future2); t2.start(); final Future future3 = pool.lease("otherhost", null); final GetPoolEntryThread t3 = new GetPoolEntryThread(future3); t3.start(); t1.join(GRACE_PERIOD); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = t1.getEntry(); Assert.assertNotNull(entry1); t2.join(GRACE_PERIOD); Assert.assertTrue(future2.isDone()); final LocalPoolEntry entry2 = t2.getEntry(); Assert.assertNotNull(entry2); t3.join(GRACE_PERIOD); Assert.assertTrue(future3.isDone()); final LocalPoolEntry entry3 = t3.getEntry(); Assert.assertNotNull(entry3); pool.release(entry1, true); pool.release(entry2, true); pool.release(entry3, true); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(3, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); final Future future4 = pool.lease("somehost", null); final GetPoolEntryThread t4 = new GetPoolEntryThread(future4); t4.start(); final Future future5 = pool.lease("somehost", null); final GetPoolEntryThread t5 = new GetPoolEntryThread(future5); t5.start(); final Future future6 = pool.lease("otherhost", null); final GetPoolEntryThread t6 = new GetPoolEntryThread(future6); t6.start(); t4.join(GRACE_PERIOD); Assert.assertTrue(future4.isDone()); final LocalPoolEntry entry4 = t4.getEntry(); Assert.assertNotNull(entry4); t5.join(GRACE_PERIOD); Assert.assertTrue(future5.isDone()); final LocalPoolEntry entry5 = t5.getEntry(); Assert.assertNotNull(entry5); t6.join(GRACE_PERIOD); Assert.assertTrue(future6.isDone()); final LocalPoolEntry entry6 = t6.getEntry(); Assert.assertNotNull(entry6); final Future future7 = pool.lease("somehost", null); final GetPoolEntryThread t7 = new GetPoolEntryThread(future7); t7.start(); final Future future8 = pool.lease("somehost", null); final GetPoolEntryThread t8 = new GetPoolEntryThread(future8); t8.start(); final Future future9 = pool.lease("otherhost", null); final GetPoolEntryThread t9 = new GetPoolEntryThread(future9); t9.start(); Assert.assertFalse(t7.isDone()); Assert.assertFalse(t8.isDone()); Assert.assertFalse(t9.isDone()); Mockito.verify(connFactory, Mockito.times(3)).create(Mockito.any(String.class)); pool.release(entry4, true); pool.release(entry5, false); pool.release(entry6, true); t7.join(); Assert.assertTrue(future7.isDone()); t8.join(); Assert.assertTrue(future8.isDone()); t9.join(); Assert.assertTrue(future9.isDone()); Mockito.verify(connFactory, Mockito.times(4)).create(Mockito.any(String.class)); } @Test public void testConnectionRedistributionOnTotalMaxLimit() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); Mockito.when(conn2.isOpen()).thenReturn(true); final HttpConnection conn3 = Mockito.mock(HttpConnection.class); Mockito.when(conn3.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1, conn2, conn3); final HttpConnection conn4 = Mockito.mock(HttpConnection.class); Mockito.when(conn4.isOpen()).thenReturn(true); final HttpConnection conn5 = Mockito.mock(HttpConnection.class); Mockito.when(conn5.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("otherhost"))).thenReturn(conn4, conn5); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); pool.setMaxPerRoute("somehost", 2); pool.setMaxPerRoute("otherhost", 2); pool.setMaxTotal(2); final Future future1 = pool.lease("somehost", null); final GetPoolEntryThread t1 = new GetPoolEntryThread(future1); t1.start(); final Future future2 = pool.lease("somehost", null); final GetPoolEntryThread t2 = new GetPoolEntryThread(future2); t2.start(); t1.join(GRACE_PERIOD); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = t1.getEntry(); Assert.assertNotNull(entry1); t2.join(GRACE_PERIOD); Assert.assertTrue(future2.isDone()); final LocalPoolEntry entry2 = t2.getEntry(); Assert.assertNotNull(entry2); final Future future3 = pool.lease("otherhost", null); final GetPoolEntryThread t3 = new GetPoolEntryThread(future3); t3.start(); final Future future4 = pool.lease("otherhost", null); final GetPoolEntryThread t4 = new GetPoolEntryThread(future4); t4.start(); Assert.assertFalse(t3.isDone()); Assert.assertFalse(t4.isDone()); Mockito.verify(connFactory, Mockito.times(2)).create(Mockito.eq("somehost")); Mockito.verify(connFactory, Mockito.never()).create(Mockito.eq("otherhost")); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(2, totals.getLeased()); pool.release(entry1, true); pool.release(entry2, true); t3.join(GRACE_PERIOD); Assert.assertTrue(future3.isDone()); final LocalPoolEntry entry3 = t3.getEntry(); Assert.assertNotNull(entry3); t4.join(GRACE_PERIOD); Assert.assertTrue(future4.isDone()); final LocalPoolEntry entry4 = t4.getEntry(); Assert.assertNotNull(entry4); Mockito.verify(connFactory, Mockito.times(2)).create(Mockito.eq("somehost")); Mockito.verify(connFactory, Mockito.times(2)).create(Mockito.eq("otherhost")); totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(2, totals.getLeased()); final Future future5 = pool.lease("somehost", null); final GetPoolEntryThread t5 = new GetPoolEntryThread(future5); t5.start(); final Future future6 = pool.lease("otherhost", null); final GetPoolEntryThread t6 = new GetPoolEntryThread(future6); t6.start(); pool.release(entry3, true); pool.release(entry4, true); t5.join(GRACE_PERIOD); Assert.assertTrue(future5.isDone()); final LocalPoolEntry entry5 = t5.getEntry(); Assert.assertNotNull(entry5); t6.join(GRACE_PERIOD); Assert.assertTrue(future6.isDone()); final LocalPoolEntry entry6 = t6.getEntry(); Assert.assertNotNull(entry6); Mockito.verify(connFactory, Mockito.times(3)).create(Mockito.eq("somehost")); Mockito.verify(connFactory, Mockito.times(2)).create(Mockito.eq("otherhost")); totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(2, totals.getLeased()); pool.release(entry5, true); pool.release(entry6, true); totals = pool.getTotalStats(); Assert.assertEquals(2, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); } @Test public void testStatefulConnectionRedistributionOnPerRouteMaxLimit() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); Mockito.when(conn2.isOpen()).thenReturn(true); final HttpConnection conn3 = Mockito.mock(HttpConnection.class); Mockito.when(conn3.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1, conn2, conn3); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); pool.setMaxPerRoute("somehost", 2); pool.setMaxTotal(2); final Future future1 = pool.lease("somehost", null); final GetPoolEntryThread t1 = new GetPoolEntryThread(future1); t1.start(); t1.join(GRACE_PERIOD); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = t1.getEntry(); Assert.assertNotNull(entry1); final Future future2 = pool.lease("somehost", null); final GetPoolEntryThread t2 = new GetPoolEntryThread(future2); t2.start(); t2.join(GRACE_PERIOD); Assert.assertTrue(future2.isDone()); final LocalPoolEntry entry2 = t2.getEntry(); Assert.assertNotNull(entry2); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(2, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); entry1.setState("some-stuff"); pool.release(entry1, true); entry2.setState("some-stuff"); pool.release(entry2, true); Mockito.verify(connFactory, Mockito.times(2)).create(Mockito.eq("somehost")); final Future future3 = pool.lease("somehost", "some-other-stuff"); final GetPoolEntryThread t3 = new GetPoolEntryThread(future3); t3.start(); t3.join(GRACE_PERIOD); Assert.assertTrue(future3.isDone()); final LocalPoolEntry entry3 = t3.getEntry(); Assert.assertNotNull(entry3); Mockito.verify(connFactory, Mockito.times(3)).create(Mockito.eq("somehost")); Mockito.verify(conn1).close(); Mockito.verify(conn2, Mockito.never()).close(); totals = pool.getTotalStats(); Assert.assertEquals(1, totals.getAvailable()); Assert.assertEquals(1, totals.getLeased()); } @Test public void testCreateNewIfExpired() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2); final Future future1 = pool.lease("somehost", null); final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry1); Mockito.verify(connFactory, Mockito.times(1)).create(Mockito.eq("somehost")); entry1.updateExpiry(1, TimeUnit.MILLISECONDS); pool.release(entry1, true); Thread.sleep(200L); final Future future2 = pool.lease("somehost", null); final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry2); Mockito.verify(connFactory, Mockito.times(2)).create(Mockito.eq("somehost")); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(1, totals.getLeased()); final PoolStats stats = pool.getStats("somehost"); Assert.assertEquals(0, stats.getAvailable()); Assert.assertEquals(1, stats.getLeased()); } @Test public void testCloseExpired() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(Boolean.FALSE); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); Mockito.when(conn2.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1, conn2); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2); final Future future1 = pool.lease("somehost", null); final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry1); final Future future2 = pool.lease("somehost", null); final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry2); entry1.updateExpiry(1, TimeUnit.MILLISECONDS); pool.release(entry1, true); Thread.sleep(200); entry2.updateExpiry(1000, TimeUnit.SECONDS); pool.release(entry2, true); pool.closeExpired(); Mockito.verify(conn1).close(); Mockito.verify(conn2, Mockito.never()).close(); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(1, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); final PoolStats stats = pool.getStats("somehost"); Assert.assertEquals(1, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); } @Test public void testLeaseTimeout() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1); final LocalConnPool pool = new LocalConnPool(connFactory, 1, 1); final Future future1 = pool.lease("somehost", null); final GetPoolEntryThread t1 = new GetPoolEntryThread(future1); t1.start(); t1.join(GRACE_PERIOD); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = t1.getEntry(); Assert.assertNotNull(entry1); final Future future2 = pool.lease("somehost", null); final GetPoolEntryThread t2 = new GetPoolEntryThread(future2, 50, TimeUnit.MICROSECONDS); t2.start(); t2.join(GRACE_PERIOD); Assert.assertTrue(t2.getException() instanceof TimeoutException); Assert.assertFalse(future2.isDone()); Assert.assertFalse(future2.isCancelled()); } @Test public void testLeaseIOException() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); Mockito.doThrow(new IOException("Oppsie")).when(connFactory).create("somehost"); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); final Future future1 = pool.lease("somehost", null); final GetPoolEntryThread t1 = new GetPoolEntryThread(future1); t1.start(); t1.join(GRACE_PERIOD); Assert.assertTrue(future1.isDone()); Assert.assertTrue(t1.getException() instanceof ExecutionException); Assert.assertTrue(t1.getException().getCause() instanceof IOException); Assert.assertFalse(future1.isCancelled()); } @Test public void testLeaseCancel() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1); final LocalConnPool pool = new LocalConnPool(connFactory, 1, 1); final Future future1 = pool.lease("somehost", null); final GetPoolEntryThread t1 = new GetPoolEntryThread(future1); t1.start(); t1.join(GRACE_PERIOD); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = t1.getEntry(); Assert.assertNotNull(entry1); final Future future2 = pool.lease("somehost", null); final GetPoolEntryThread t2 = new GetPoolEntryThread(future2); t2.start(); Thread.sleep(5); Assert.assertFalse(future2.isDone()); Assert.assertFalse(future2.isCancelled()); future2.cancel(true); t2.join(GRACE_PERIOD); Assert.assertTrue(future2.isDone()); Assert.assertTrue(future2.isCancelled()); future2.cancel(true); future2.cancel(true); } @Test public void testCloseIdle() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); Mockito.when(conn2.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1, conn2); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2); final Future future1 = pool.lease("somehost", null); final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry1); final Future future2 = pool.lease("somehost", null); final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry2); entry1.updateExpiry(0, TimeUnit.MILLISECONDS); pool.release(entry1, true); Thread.sleep(200L); entry2.updateExpiry(0, TimeUnit.MILLISECONDS); pool.release(entry2, true); pool.closeIdle(50, TimeUnit.MILLISECONDS); Mockito.verify(conn1).close(); Mockito.verify(conn2, Mockito.never()).close(); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(1, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); PoolStats stats = pool.getStats("somehost"); Assert.assertEquals(1, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); pool.closeIdle(-1, TimeUnit.MILLISECONDS); Mockito.verify(conn2).close(); totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); stats = pool.getStats("somehost"); Assert.assertEquals(0, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); } @Test(expected=IllegalArgumentException.class) public void testCloseIdleInvalid() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2); pool.closeIdle(50, null); } @Test(expected=IllegalArgumentException.class) public void testGetStatsInvalid() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2); pool.getStats(null); } @Test public void testSetMaxInvalid() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2); try { pool.setMaxTotal(-1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { pool.setMaxPerRoute(null, 1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { pool.setMaxPerRoute("somehost", -1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { pool.setDefaultMaxPerRoute(-1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } } @Test public void testShutdown() throws Exception { final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); Mockito.when(conn1.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); Mockito.when(conn2.isOpen()).thenReturn(true); Mockito.when(connFactory.create(Mockito.eq("otherhost"))).thenReturn(conn2); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2); final Future future1 = pool.lease("somehost", null); final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry1); final Future future2 = pool.lease("otherhost", null); final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry2); pool.release(entry2, true); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(1, totals.getAvailable()); Assert.assertEquals(1, totals.getLeased()); pool.shutdown(); Assert.assertTrue(pool.isShutdown()); pool.shutdown(); pool.shutdown(); Mockito.verify(conn1, Mockito.atLeastOnce()).close(); Mockito.verify(conn2, Mockito.atLeastOnce()).close(); try { pool.lease("somehost", null); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException expected) { } // Ignored if shut down pool.release(new LocalPoolEntry("somehost", Mockito.mock(HttpConnection.class)), true); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/pool/TestPoolEntry.java0100644 0000000 0000000 00000011575 12276755417 030230 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.pool; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.http.HttpConnection; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestPoolEntry { static class MockPoolEntry extends PoolEntry { public MockPoolEntry(final String route, final long timeToLive, final TimeUnit tunit) { super(null, route, Mockito.mock(HttpConnection.class), timeToLive, tunit); } public MockPoolEntry(final String route, final HttpConnection conn, final long timeToLive, final TimeUnit tunit) { super(null, route, conn, timeToLive, tunit); } @Override public void close() { try { getConnection().close(); } catch (final IOException ignore) { } } @Override public boolean isClosed() { return !getConnection().isOpen(); } } @Test public void testBasics() throws Exception { final MockPoolEntry entry1 = new MockPoolEntry("route1", 10L, TimeUnit.MILLISECONDS); final long now = System.currentTimeMillis(); Assert.assertEquals("route1", entry1.getRoute()); Assert.assertTrue(now >= entry1.getCreated()); Assert.assertEquals(entry1.getValidUnit(), entry1.getExpiry()); Assert.assertEquals(entry1.getCreated() + 10L, entry1.getValidUnit()); } @Test public void testInvalidConstruction() throws Exception { try { new MockPoolEntry(null, Mockito.mock(HttpConnection.class), 0L, TimeUnit.MILLISECONDS); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { new MockPoolEntry("stuff", null, 0L, TimeUnit.MILLISECONDS); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { new MockPoolEntry("stuff", Mockito.mock(HttpConnection.class), 0L, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } } @Test public void testValidInfinitely() throws Exception { final MockPoolEntry entry1 = new MockPoolEntry("route1", 0L, TimeUnit.MILLISECONDS); Assert.assertEquals(Long.MAX_VALUE, entry1.getValidUnit()); Assert.assertEquals(entry1.getValidUnit(), entry1.getExpiry()); } @Test public void testExpiry() throws Exception { final MockPoolEntry entry1 = new MockPoolEntry("route1", 0L, TimeUnit.MILLISECONDS); Assert.assertEquals(Long.MAX_VALUE, entry1.getExpiry()); entry1.updateExpiry(50L, TimeUnit.MILLISECONDS); Assert.assertEquals(entry1.getUpdated() + 50L, entry1.getExpiry()); entry1.updateExpiry(0L, TimeUnit.MILLISECONDS); Assert.assertEquals(Long.MAX_VALUE, entry1.getExpiry()); final MockPoolEntry entry2 = new MockPoolEntry("route1", 100L, TimeUnit.MILLISECONDS); Assert.assertEquals(entry2.getCreated() + 100L, entry2.getExpiry()); entry2.updateExpiry(150L, TimeUnit.MILLISECONDS); Assert.assertEquals(entry2.getCreated() + 100L, entry2.getExpiry()); entry2.updateExpiry(50L, TimeUnit.MILLISECONDS); Assert.assertEquals(entry2.getUpdated() + 50L, entry2.getExpiry()); } @Test(expected=IllegalArgumentException.class) public void testInvalidExpiry() throws Exception { final MockPoolEntry entry1 = new MockPoolEntry("route1", 0L, TimeUnit.MILLISECONDS); entry1.updateExpiry(50L, null); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/pool/TestRouteSpecificPool.java0100644 0000000 0000000 00000031205 12276755417 031663 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.pool; import java.io.IOException; import org.apache.http.HttpConnection; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestRouteSpecificPool { private static final String ROUTE = "whatever"; static class LocalPoolEntry extends PoolEntry { public LocalPoolEntry(final String route, final HttpConnection conn) { super(null, route, conn); } @Override public void close() { try { getConnection().close(); } catch (final IOException ignore) { } } @Override public boolean isClosed() { return !getConnection().isOpen(); } } static class LocalRoutePool extends RouteSpecificPool { public LocalRoutePool() { super(ROUTE); } @Override protected LocalPoolEntry createEntry(final HttpConnection conn) { return new LocalPoolEntry(getRoute(), conn); } } @Test public void testEmptyPool() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); Assert.assertEquals(ROUTE, pool.getRoute()); Assert.assertEquals(0, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); Assert.assertNull(pool.getLastUsed()); Assert.assertEquals("[route: whatever][leased: 0][available: 0][pending: 0]", pool.toString()); } @Test public void testAdd() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final HttpConnection conn = Mockito.mock(HttpConnection.class); final PoolEntry entry = pool.add(conn); Assert.assertEquals(1, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(1, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); Assert.assertNotNull(entry); Assert.assertSame(conn, entry.getConnection()); } @Test public void testLeaseRelease() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry1 = pool.add(conn1); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry2 = pool.add(conn2); final HttpConnection conn3 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry3 = pool.add(conn3); Assert.assertNotNull(entry1); Assert.assertNotNull(entry2); Assert.assertNotNull(entry3); Assert.assertEquals(3, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(3, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); pool.free(entry1, true); pool.free(entry2, false); pool.free(entry3, true); Assert.assertEquals(2, pool.getAllocatedCount()); Assert.assertEquals(2, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); Assert.assertSame(entry1, pool.getLastUsed()); Assert.assertNotNull(pool.getFree(null)); Assert.assertNotNull(pool.getFree(null)); Assert.assertNull(pool.getFree(null)); Assert.assertEquals(2, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(2, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); } @Test public void testLeaseOrder() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry1 = pool.add(conn1); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry2 = pool.add(conn2); final HttpConnection conn3 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry3 = pool.add(conn3); Assert.assertNotNull(entry1); Assert.assertNotNull(entry2); Assert.assertNotNull(entry3); Assert.assertEquals(3, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(3, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); pool.free(entry1, true); pool.free(entry2, true); pool.free(entry3, true); Assert.assertSame(entry1, pool.getLastUsed()); Assert.assertSame(entry3, pool.getFree(null)); Assert.assertSame(entry2, pool.getFree(null)); Assert.assertSame(entry1, pool.getFree(null)); } @Test public void testLeaseReleaseStateful() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry1 = pool.add(conn1); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry2 = pool.add(conn2); final HttpConnection conn3 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry3 = pool.add(conn3); Assert.assertNotNull(entry1); Assert.assertNotNull(entry2); Assert.assertNotNull(entry3); Assert.assertEquals(3, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(3, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); entry2.setState(Boolean.FALSE); pool.free(entry1, true); pool.free(entry2, true); pool.free(entry3, true); Assert.assertSame(entry2, pool.getFree(Boolean.FALSE)); Assert.assertSame(entry3, pool.getFree(Boolean.FALSE)); Assert.assertSame(entry1, pool.getFree(null)); Assert.assertSame(null, pool.getFree(null)); entry1.setState(Boolean.TRUE); entry2.setState(Boolean.FALSE); entry3.setState(Boolean.TRUE); pool.free(entry1, true); pool.free(entry2, true); pool.free(entry3, true); Assert.assertSame(null, pool.getFree(null)); Assert.assertSame(entry2, pool.getFree(Boolean.FALSE)); Assert.assertSame(null, pool.getFree(Boolean.FALSE)); Assert.assertSame(entry3, pool.getFree(Boolean.TRUE)); Assert.assertSame(entry1, pool.getFree(Boolean.TRUE)); Assert.assertSame(null, pool.getFree(Boolean.TRUE)); } @Test(expected=IllegalStateException.class) public void testReleaseInvalidEntry() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final HttpConnection conn = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry = new LocalPoolEntry(ROUTE, conn); pool.free(entry, true); } @Test public void testRemove() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry1 = pool.add(conn1); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry2 = pool.add(conn2); final HttpConnection conn3 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry3 = pool.add(conn3); Assert.assertNotNull(entry1); Assert.assertNotNull(entry2); Assert.assertNotNull(entry3); Assert.assertEquals(3, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(3, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); Assert.assertTrue(pool.remove(entry2)); Assert.assertFalse(pool.remove(entry2)); Assert.assertEquals(2, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(2, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); pool.free(entry1, true); pool.free(entry3, true); Assert.assertEquals(2, pool.getAllocatedCount()); Assert.assertEquals(2, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); Assert.assertTrue(pool.remove(entry1)); Assert.assertTrue(pool.remove(entry3)); Assert.assertEquals(0, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); } @Test(expected=IllegalArgumentException.class) public void testReleaseInvalid() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); pool.free(null, true); } @Test(expected=IllegalArgumentException.class) public void testRemoveInvalid() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); pool.remove(null); } @Test public void testWaitingThreadQueuing() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); @SuppressWarnings("unchecked") final PoolEntryFuture future1 = Mockito.mock(PoolEntryFuture.class); @SuppressWarnings("unchecked") final PoolEntryFuture future2 = Mockito.mock(PoolEntryFuture.class); Assert.assertEquals(0, pool.getPendingCount()); pool.queue(future1); Assert.assertEquals(1, pool.getPendingCount()); pool.queue(null); Assert.assertEquals(1, pool.getPendingCount()); pool.queue(future2); Assert.assertEquals(2, pool.getPendingCount()); Assert.assertSame(future1, pool.nextPending()); pool.unqueue(future1); Assert.assertEquals(1, pool.getPendingCount()); Assert.assertSame(future2, pool.nextPending()); pool.unqueue(null); Assert.assertEquals(0, pool.getPendingCount()); pool.unqueue(future2); Assert.assertNull(pool.nextPending()); } @Test public void testShutdown() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final HttpConnection conn1 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry1 = pool.add(conn1); final HttpConnection conn2 = Mockito.mock(HttpConnection.class); final LocalPoolEntry entry2 = pool.add(conn2); @SuppressWarnings("unchecked") final PoolEntryFuture future1 = Mockito.mock(PoolEntryFuture.class); pool.queue(future1); Assert.assertNotNull(entry1); Assert.assertNotNull(entry2); pool.free(entry1, true); Assert.assertEquals(2, pool.getAllocatedCount()); Assert.assertEquals(1, pool.getAvailableCount()); Assert.assertEquals(1, pool.getLeasedCount()); Assert.assertEquals(1, pool.getPendingCount()); pool.shutdown(); Assert.assertEquals(0, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); Mockito.verify(future1).cancel(true); Mockito.verify(conn2).close(); Mockito.verify(conn1).close(); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/0040755 0000000 0000000 00000000000 12276755422 025233 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHttpResponse.java0100644 0000000 0000000 00000011360 12276755422 032334 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HttpVersion; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link BasicHttpResponse}. */ public class TestBasicHttpResponse { @Test public void testBasics() { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion()); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertEquals("OK", response.getStatusLine().getReasonPhrase()); } @Test public void testStatusLineMutation() { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertEquals("OK", response.getStatusLine().getReasonPhrase()); response.setReasonPhrase("Kind of OK"); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertEquals("Kind of OK", response.getStatusLine().getReasonPhrase()); response.setStatusCode(299); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(299, response.getStatusLine().getStatusCode()); Assert.assertEquals(null, response.getStatusLine().getReasonPhrase()); response.setStatusLine(HttpVersion.HTTP_1_0, 298); Assert.assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(298, response.getStatusLine().getStatusCode()); Assert.assertEquals(null, response.getStatusLine().getReasonPhrase()); response.setStatusLine(HttpVersion.HTTP_1_1, 200, "OK"); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertEquals("OK", response.getStatusLine().getReasonPhrase()); response.setStatusLine(new BasicStatusLine(HttpVersion.HTTP_1_0, 500, "Boom")); Assert.assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(500, response.getStatusLine().getStatusCode()); Assert.assertEquals("Boom", response.getStatusLine().getReasonPhrase()); } @Test public void testInvalidStatusCode() { try { new BasicHttpResponse(HttpVersion.HTTP_1_1, -200, "OK"); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); try { response.setStatusCode(-1); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { response.setStatusLine(HttpVersion.HTTP_1_1, -1); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } try { response.setStatusLine(HttpVersion.HTTP_1_1, -1, "not ok"); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException expected) { } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestHeader.java0100644 0000000 0000000 00000011013 12276755422 030117 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link Header}. */ public class TestHeader { @Test public void testBasicConstructor() { final Header header = new BasicHeader("name", "value"); Assert.assertEquals("name", header.getName()); Assert.assertEquals("value", header.getValue()); } @Test public void testBasicConstructorNullValue() { final Header header = new BasicHeader("name", null); Assert.assertEquals("name", header.getName()); Assert.assertEquals(null, header.getValue()); } @Test public void testInvalidName() { try { new BasicHeader(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { //expected } } @Test public void testToString() { final Header header1 = new BasicHeader("name1", "value1"); Assert.assertEquals("name1: value1", header1.toString()); final Header header2 = new BasicHeader("name2", null); Assert.assertEquals("name2: ", header2.toString()); } @Test public void testHeaderElements() { Header header = new BasicHeader("name", "element1 = value1, element2; param1 = value1, element3"); HeaderElement[] elements = header.getElements(); Assert.assertNotNull(elements); Assert.assertEquals(3, elements.length); Assert.assertEquals("element1", elements[0].getName()); Assert.assertEquals("value1", elements[0].getValue()); Assert.assertEquals("element2", elements[1].getName()); Assert.assertEquals(null, elements[1].getValue()); Assert.assertEquals("element3", elements[2].getName()); Assert.assertEquals(null, elements[2].getValue()); Assert.assertEquals(1, elements[1].getParameters().length); header = new BasicHeader("name", null); elements = header.getElements(); Assert.assertNotNull(elements); Assert.assertEquals(0, elements.length); } @Test public void testCloning() throws Exception { final BasicHeader orig = new BasicHeader("name1", "value1"); final BasicHeader clone = (BasicHeader) orig.clone(); Assert.assertEquals(orig.getName(), clone.getName()); Assert.assertEquals(orig.getValue(), clone.getValue()); } @Test public void testSerialization() throws Exception { final BasicHeader orig = new BasicHeader("name1", "value1"); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final BasicHeader clone = (BasicHeader) instream.readObject(); Assert.assertEquals(orig.getName(), clone.getName()); Assert.assertEquals(orig.getValue(), clone.getValue()); } } ././@LongLink0100644 0000000 0000000 00000000151 12276757361 011650 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderValueParser.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderValueParser.0100644 0000000 0000000 00000034675 12276755422 032414 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.apache.http.util.CharArrayBuffer; import org.junit.Assert; import org.junit.Test; /** * Tests for header value parsing. * * @version $Id: TestBasicHeaderValueParser.java 1433815 2013-01-16 03:27:44Z ggregory $ */ public class TestBasicHeaderValueParser { @Test public void testParseHeaderElements() throws Exception { final String headerValue = "name1 = value1; name2; name3=\"value3\" , name4=value4; " + "name5=value5, name6= ; name7 = value7; name8 = \" value8\""; final HeaderElement[] elements = BasicHeaderValueParser.parseElements(headerValue, null); // there are 3 elements Assert.assertEquals(3,elements.length); // 1st element Assert.assertEquals("name1",elements[0].getName()); Assert.assertEquals("value1",elements[0].getValue()); // 1st element has 2 getParameters() Assert.assertEquals(2,elements[0].getParameters().length); Assert.assertEquals("name2",elements[0].getParameters()[0].getName()); Assert.assertEquals(null, elements[0].getParameters()[0].getValue()); Assert.assertEquals("name3",elements[0].getParameters()[1].getName()); Assert.assertEquals("value3",elements[0].getParameters()[1].getValue()); // 2nd element Assert.assertEquals("name4",elements[1].getName()); Assert.assertEquals("value4",elements[1].getValue()); // 2nd element has 1 parameter Assert.assertEquals(1,elements[1].getParameters().length); Assert.assertEquals("name5",elements[1].getParameters()[0].getName()); Assert.assertEquals("value5",elements[1].getParameters()[0].getValue()); // 3rd element Assert.assertEquals("name6",elements[2].getName()); Assert.assertEquals("",elements[2].getValue()); // 3rd element has 2 getParameters() Assert.assertEquals(2,elements[2].getParameters().length); Assert.assertEquals("name7",elements[2].getParameters()[0].getName()); Assert.assertEquals("value7",elements[2].getParameters()[0].getValue()); Assert.assertEquals("name8",elements[2].getParameters()[1].getName()); Assert.assertEquals(" value8",elements[2].getParameters()[1].getValue()); } @Test public void testParseHEEscaped() { final String s = "test1 = \"\\\"stuff\\\"\", test2= \"\\\\\", test3 = \"stuff, stuff\""; final HeaderElement[] elements = BasicHeaderValueParser.parseElements(s, null); Assert.assertEquals(3, elements.length); Assert.assertEquals("test1", elements[0].getName()); Assert.assertEquals("\\\"stuff\\\"", elements[0].getValue()); Assert.assertEquals("test2", elements[1].getName()); Assert.assertEquals("\\\\", elements[1].getValue()); Assert.assertEquals("test3", elements[2].getName()); Assert.assertEquals("stuff, stuff", elements[2].getValue()); } @Test public void testHEFringeCase1() throws Exception { final String headerValue = "name1 = value1,"; final HeaderElement[] elements = BasicHeaderValueParser.parseElements(headerValue, null); Assert.assertEquals("Number of elements", 1, elements.length); } @Test public void testHEFringeCase2() throws Exception { final String headerValue = "name1 = value1, "; final HeaderElement[] elements = BasicHeaderValueParser.parseElements(headerValue, null); Assert.assertEquals("Number of elements", 1, elements.length); } @Test public void testHEFringeCase3() throws Exception { final String headerValue = ",, ,, ,"; final HeaderElement[] elements = BasicHeaderValueParser.parseElements(headerValue, null); Assert.assertEquals("Number of elements", 0, elements.length); } @Test public void testNVParseUsingCursor() { final HeaderValueParser parser = BasicHeaderValueParser.INSTANCE; String s = "test"; CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append(s); ParserCursor cursor = new ParserCursor(0, s.length()); NameValuePair param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals(null, param.getValue()); Assert.assertEquals(s.length(), cursor.getPos()); Assert.assertTrue(cursor.atEnd()); s = "test;"; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals(null, param.getValue()); Assert.assertEquals(s.length(), cursor.getPos()); Assert.assertTrue(cursor.atEnd()); s = "test ,12"; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals(null, param.getValue()); Assert.assertEquals(s.length() - 2, cursor.getPos()); Assert.assertFalse(cursor.atEnd()); s = "test=stuff"; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals("stuff", param.getValue()); Assert.assertEquals(s.length(), cursor.getPos()); Assert.assertTrue(cursor.atEnd()); s = " test = stuff "; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals("stuff", param.getValue()); Assert.assertEquals(s.length(), cursor.getPos()); Assert.assertTrue(cursor.atEnd()); s = " test = stuff ;1234"; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals("stuff", param.getValue()); Assert.assertEquals(s.length() - 4, cursor.getPos()); Assert.assertFalse(cursor.atEnd()); s = "test = \"stuff\""; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals("stuff", param.getValue()); s = "test = \" stuff\\\"\""; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals(" stuff\\\"", param.getValue()); s = " test"; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("test", param.getName()); Assert.assertEquals(null, param.getValue()); s = " "; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("", param.getName()); Assert.assertEquals(null, param.getValue()); s = " = stuff "; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); param = parser.parseNameValuePair(buffer, cursor); Assert.assertEquals("", param.getName()); Assert.assertEquals("stuff", param.getValue()); } @Test public void testNVParse() { String s = "test"; NameValuePair param = BasicHeaderValueParser.parseNameValuePair(s, null); Assert.assertEquals("test", param.getName()); Assert.assertEquals(null, param.getValue()); s = "test=stuff"; param = BasicHeaderValueParser.parseNameValuePair(s, null); Assert.assertEquals("test", param.getName()); Assert.assertEquals("stuff", param.getValue()); s = " test = stuff "; param = BasicHeaderValueParser.parseNameValuePair(s, null); Assert.assertEquals("test", param.getName()); Assert.assertEquals("stuff", param.getValue()); s = "test = \"stuff\""; param = BasicHeaderValueParser.parseNameValuePair(s, null); Assert.assertEquals("test", param.getName()); Assert.assertEquals("stuff", param.getValue()); s = "test = \" stuff\\\"\""; param = BasicHeaderValueParser.parseNameValuePair(s, null); Assert.assertEquals("test", param.getName()); Assert.assertEquals(" stuff\\\"", param.getValue()); s = " test"; param = BasicHeaderValueParser.parseNameValuePair(s, null); Assert.assertEquals("test", param.getName()); Assert.assertEquals(null, param.getValue()); s = " "; param = BasicHeaderValueParser.parseNameValuePair(s, null); Assert.assertEquals("", param.getName()); Assert.assertEquals(null, param.getValue()); s = " = stuff "; param = BasicHeaderValueParser.parseNameValuePair(s, null); Assert.assertEquals("", param.getName()); Assert.assertEquals("stuff", param.getValue()); } @Test public void testNVParseAllWithCursor() { final HeaderValueParser parser = BasicHeaderValueParser.INSTANCE; String s = "test; test1 = stuff ; test2 = \"stuff; stuff\"; test3=\"stuff"; CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append(s); ParserCursor cursor = new ParserCursor(0, s.length()); NameValuePair[] params = parser.parseParameters(buffer, cursor); Assert.assertEquals("test", params[0].getName()); Assert.assertEquals(null, params[0].getValue()); Assert.assertEquals("test1", params[1].getName()); Assert.assertEquals("stuff", params[1].getValue()); Assert.assertEquals("test2", params[2].getName()); Assert.assertEquals("stuff; stuff", params[2].getValue()); Assert.assertEquals("test3", params[3].getName()); Assert.assertEquals("\"stuff", params[3].getValue()); Assert.assertEquals(s.length(), cursor.getPos()); Assert.assertTrue(cursor.atEnd()); s = "test; test1 = stuff ; test2 = \"stuff; stuff\"; test3=\"stuff\",123"; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); params = parser.parseParameters(buffer, cursor); Assert.assertEquals("test", params[0].getName()); Assert.assertEquals(null, params[0].getValue()); Assert.assertEquals("test1", params[1].getName()); Assert.assertEquals("stuff", params[1].getValue()); Assert.assertEquals("test2", params[2].getName()); Assert.assertEquals("stuff; stuff", params[2].getValue()); Assert.assertEquals("test3", params[3].getName()); Assert.assertEquals("stuff", params[3].getValue()); Assert.assertEquals(s.length() - 3, cursor.getPos()); Assert.assertFalse(cursor.atEnd()); s = " "; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); params = parser.parseParameters(buffer, cursor); Assert.assertEquals(0, params.length); } @Test public void testNVParseAll() { String s = "test; test1 = stuff ; test2 = \"stuff; stuff\"; test3=\"stuff"; NameValuePair[] params = BasicHeaderValueParser.parseParameters(s, null); Assert.assertEquals("test", params[0].getName()); Assert.assertEquals(null, params[0].getValue()); Assert.assertEquals("test1", params[1].getName()); Assert.assertEquals("stuff", params[1].getValue()); Assert.assertEquals("test2", params[2].getName()); Assert.assertEquals("stuff; stuff", params[2].getValue()); Assert.assertEquals("test3", params[3].getName()); Assert.assertEquals("\"stuff", params[3].getValue()); s = " "; params = BasicHeaderValueParser.parseParameters(s, null); Assert.assertEquals(0, params.length); } @Test public void testNVParseEscaped() { final String s = "test1 = \"\\\"stuff\\\"\"; test2= \"\\\\\"; test3 = \"stuff; stuff\""; final NameValuePair[] params = BasicHeaderValueParser.parseParameters(s, null); Assert.assertEquals(3, params.length); Assert.assertEquals("test1", params[0].getName()); Assert.assertEquals("\\\"stuff\\\"", params[0].getValue()); Assert.assertEquals("test2", params[1].getName()); Assert.assertEquals("\\\\", params[1].getValue()); Assert.assertEquals("test3", params[2].getName()); Assert.assertEquals("stuff; stuff", params[2].getValue()); } } ././@LongLink0100644 0000000 0000000 00000000154 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderValueFormatter.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderValueFormatt0100644 0000000 0000000 00000021374 12276755422 032506 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.junit.Assert; import org.junit.Test; /** * Tests for header value formatting. * * */ public class TestBasicHeaderValueFormatter { @Test public void testNVPFormatting() throws Exception { final NameValuePair param1 = new BasicNameValuePair("param", "regular_stuff"); final NameValuePair param2 = new BasicNameValuePair("param", "this\\that"); final NameValuePair param3 = new BasicNameValuePair("param", "this,that"); final NameValuePair param4 = new BasicNameValuePair("param", "quote marks (\") must be escaped"); final NameValuePair param5 = new BasicNameValuePair("param", "back slash (\\) must be escaped too"); final NameValuePair param6 = new BasicNameValuePair("param", "values with\tblanks must always be quoted"); final NameValuePair param7 = new BasicNameValuePair("param", null); Assert.assertEquals("param=regular_stuff", BasicHeaderValueFormatter.formatNameValuePair (param1, false, null)); Assert.assertEquals("param=\"this\\\\that\"", BasicHeaderValueFormatter.formatNameValuePair (param2, false, null)); Assert.assertEquals("param=\"this,that\"", BasicHeaderValueFormatter.formatNameValuePair (param3, false, null)); Assert.assertEquals("param=\"quote marks (\\\") must be escaped\"", BasicHeaderValueFormatter.formatNameValuePair (param4, false, null)); Assert.assertEquals("param=\"back slash (\\\\) must be escaped too\"", BasicHeaderValueFormatter.formatNameValuePair (param5, false, null)); Assert.assertEquals("param=\"values with\tblanks must always be quoted\"", BasicHeaderValueFormatter.formatNameValuePair (param6, false, null)); Assert.assertEquals("param", BasicHeaderValueFormatter.formatNameValuePair (param7, false, null)); Assert.assertEquals("param=\"regular_stuff\"", BasicHeaderValueFormatter.formatNameValuePair (param1, true, null)); Assert.assertEquals("param=\"this\\\\that\"", BasicHeaderValueFormatter.formatNameValuePair (param2, true, null)); Assert.assertEquals("param=\"this,that\"", BasicHeaderValueFormatter.formatNameValuePair (param3, true, null)); Assert.assertEquals("param=\"quote marks (\\\") must be escaped\"", BasicHeaderValueFormatter.formatNameValuePair (param4, true, null)); Assert.assertEquals("param=\"back slash (\\\\) must be escaped too\"", BasicHeaderValueFormatter.formatNameValuePair (param5, true, null)); Assert.assertEquals("param=\"values with\tblanks must always be quoted\"", BasicHeaderValueFormatter.formatNameValuePair (param6, true, null)); Assert.assertEquals("param", BasicHeaderValueFormatter.formatNameValuePair (param7, false, null)); } @Test public void testParamsFormatting() throws Exception { final NameValuePair param1 = new BasicNameValuePair("param", "regular_stuff"); final NameValuePair param2 = new BasicNameValuePair("param", "this\\that"); final NameValuePair param3 = new BasicNameValuePair("param", "this,that"); final NameValuePair[] params = new NameValuePair[] {param1, param2, param3}; Assert.assertEquals("param=regular_stuff; param=\"this\\\\that\"; param=\"this,that\"", BasicHeaderValueFormatter.formatParameters(params, false, null)); Assert.assertEquals("param=\"regular_stuff\"; param=\"this\\\\that\"; param=\"this,that\"", BasicHeaderValueFormatter.formatParameters(params, true, null)); } @Test public void testHEFormatting() throws Exception { final NameValuePair param1 = new BasicNameValuePair("param", "regular_stuff"); final NameValuePair param2 = new BasicNameValuePair("param", "this\\that"); final NameValuePair param3 = new BasicNameValuePair("param", "this,that"); final NameValuePair param4 = new BasicNameValuePair("param", null); final NameValuePair[] params = new NameValuePair[] {param1, param2, param3, param4}; final HeaderElement element = new BasicHeaderElement("name", "value", params); Assert.assertEquals("name=value; param=regular_stuff; param=\"this\\\\that\"; param=\"this,that\"; param", BasicHeaderValueFormatter.formatHeaderElement(element, false, null)); } @Test public void testElementsFormatting() throws Exception { final NameValuePair param1 = new BasicNameValuePair("param", "regular_stuff"); final NameValuePair param2 = new BasicNameValuePair("param", "this\\that"); final NameValuePair param3 = new BasicNameValuePair("param", "this,that"); final NameValuePair param4 = new BasicNameValuePair("param", null); final HeaderElement element1 = new BasicHeaderElement("name1", "value1", new NameValuePair[] {param1}); final HeaderElement element2 = new BasicHeaderElement("name2", "value2", new NameValuePair[] {param2}); final HeaderElement element3 = new BasicHeaderElement("name3", "value3", new NameValuePair[] {param3}); final HeaderElement element4 = new BasicHeaderElement("name4", "value4", new NameValuePair[] {param4}); final HeaderElement element5 = new BasicHeaderElement("name5", null); final HeaderElement[] elements = new HeaderElement[] {element1, element2, element3, element4, element5}; Assert.assertEquals ("name1=value1; param=regular_stuff, name2=value2; " + "param=\"this\\\\that\", name3=value3; param=\"this,that\", " + "name4=value4; param, name5", BasicHeaderValueFormatter.formatElements(elements, false, null)); } @Test public void testInvalidHEArguments() throws Exception { try { BasicHeaderValueFormatter.formatHeaderElement ((HeaderElement) null, false, BasicHeaderValueFormatter.INSTANCE); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { BasicHeaderValueFormatter.formatElements ((HeaderElement[]) null, false, BasicHeaderValueFormatter.INSTANCE); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testInvalidNVArguments() throws Exception { try { BasicHeaderValueFormatter.formatNameValuePair ((NameValuePair) null, true, null); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { BasicHeaderValueFormatter.formatParameters ((NameValuePair[]) null, true, BasicHeaderValueFormatter.INSTANCE); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicLineParser.java0100644 0000000 0000000 00000030576 12276755422 031754 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HttpVersion; import org.apache.http.ParseException; import org.apache.http.RequestLine; import org.apache.http.StatusLine; import org.apache.http.util.CharArrayBuffer; import org.junit.Assert; import org.junit.Test; /** * Tests for {@link BasicLineParser}. * */ public class TestBasicLineParser { @Test public void testRLParseSuccess() throws Exception { //typical request line RequestLine requestline = BasicLineParser.parseRequestLine ("GET /stuff HTTP/1.1", null); Assert.assertEquals("GET /stuff HTTP/1.1", requestline.toString()); Assert.assertEquals("GET", requestline.getMethod()); Assert.assertEquals("/stuff", requestline.getUri()); Assert.assertEquals(HttpVersion.HTTP_1_1, requestline.getProtocolVersion()); //Lots of blanks requestline = BasicLineParser.parseRequestLine (" GET /stuff HTTP/1.1 ", null); Assert.assertEquals("GET /stuff HTTP/1.1", requestline.toString()); Assert.assertEquals("GET", requestline.getMethod()); Assert.assertEquals("/stuff", requestline.getUri()); Assert.assertEquals(HttpVersion.HTTP_1_1, requestline.getProtocolVersion()); //this is not strictly valid, but is lenient requestline = BasicLineParser.parseRequestLine ("\rGET /stuff HTTP/1.1", null); Assert.assertEquals("GET", requestline.getMethod()); Assert.assertEquals("/stuff", requestline.getUri()); Assert.assertEquals(HttpVersion.HTTP_1_1, requestline.getProtocolVersion()); } @Test public void testRLParseFailure() throws Exception { try { BasicLineParser.parseRequestLine(" ", null); Assert.fail(); } catch (final ParseException e) { // expected } try { BasicLineParser.parseRequestLine(" GET", null); Assert.fail(); } catch (final ParseException e) { // expected } try { BasicLineParser.parseRequestLine("GET /stuff", null); Assert.fail(); } catch (final ParseException e) { // expected } try { BasicLineParser.parseRequestLine("GET/stuff HTTP/1.1", null); Assert.fail(); } catch (final ParseException e) { // expected } try { BasicLineParser.parseRequestLine("GET /stuff HTTP/1.1 Oooooooooooppsie", null); Assert.fail(); } catch (final ParseException e) { // expected } } @Test public void testSLParseSuccess() throws Exception { //typical status line StatusLine statusLine = BasicLineParser.parseStatusLine ("HTTP/1.1 200 OK", null); Assert.assertEquals("HTTP/1.1 200 OK", statusLine.toString()); Assert.assertEquals(HttpVersion.HTTP_1_1, statusLine.getProtocolVersion()); Assert.assertEquals(200, statusLine.getStatusCode()); Assert.assertEquals("OK", statusLine.getReasonPhrase()); //status line with multi word reason phrase statusLine = BasicLineParser.parseStatusLine ("HTTP/1.1 404 Not Found", null); Assert.assertEquals(404, statusLine.getStatusCode()); Assert.assertEquals("Not Found", statusLine.getReasonPhrase()); //reason phrase can be anyting statusLine = BasicLineParser.parseStatusLine ("HTTP/1.1 404 Non Trouve", null); Assert.assertEquals("Non Trouve", statusLine.getReasonPhrase()); //its ok to end with a \n\r statusLine = BasicLineParser.parseStatusLine ("HTTP/1.1 404 Not Found\r\n", null); Assert.assertEquals("Not Found", statusLine.getReasonPhrase()); //this is valid according to the Status-Line BNF statusLine = BasicLineParser.parseStatusLine ("HTTP/1.1 200 ", null); Assert.assertEquals(200, statusLine.getStatusCode()); Assert.assertEquals("", statusLine.getReasonPhrase()); //this is not strictly valid, but is lenient statusLine = BasicLineParser.parseStatusLine ("HTTP/1.1 200", null); Assert.assertEquals(200, statusLine.getStatusCode()); Assert.assertEquals("", statusLine.getReasonPhrase()); //this is not strictly valid, but is lenient statusLine = BasicLineParser.parseStatusLine ("HTTP/1.1 200 OK", null); Assert.assertEquals(200, statusLine.getStatusCode()); Assert.assertEquals("OK", statusLine.getReasonPhrase()); //this is not strictly valid, but is lenient statusLine = BasicLineParser.parseStatusLine ("\rHTTP/1.1 200 OK", null); Assert.assertEquals(200, statusLine.getStatusCode()); Assert.assertEquals("OK", statusLine.getReasonPhrase()); Assert.assertEquals(HttpVersion.HTTP_1_1, statusLine.getProtocolVersion()); //this is not strictly valid, but is lenient statusLine = BasicLineParser.parseStatusLine (" HTTP/1.1 200 OK", null); Assert.assertEquals(200, statusLine.getStatusCode()); Assert.assertEquals("OK", statusLine.getReasonPhrase()); Assert.assertEquals(HttpVersion.HTTP_1_1, statusLine.getProtocolVersion()); } @Test public void testSLParseFailure() throws Exception { try { BasicLineParser.parseStatusLine("xxx 200 OK", null); Assert.fail(); } catch (final ParseException e) { // expected } try { BasicLineParser.parseStatusLine("HTTP/1.1 xxx OK", null); Assert.fail(); } catch (final ParseException e) { // expected } try { BasicLineParser.parseStatusLine("HTTP/1.1 ", null); Assert.fail(); } catch (final ParseException e) { // expected } try { BasicLineParser.parseStatusLine("HTTP/1.1", null); Assert.fail(); } catch (final ParseException e) { // expected } try { BasicLineParser.parseStatusLine("HTTP/1.1 -200 OK", null); Assert.fail(); } catch (final ParseException e) { // expected } } @Test public void testHttpVersionParsing() throws Exception { String s = "HTTP/1.1"; HttpVersion version = (HttpVersion) BasicLineParser.parseProtocolVersion(s, null); Assert.assertEquals("HTTP protocol name", "HTTP", version.getProtocol()); Assert.assertEquals("HTTP major version number", 1, version.getMajor()); Assert.assertEquals("HTTP minor version number", 1, version.getMinor()); Assert.assertEquals("HTTP version number", s, version.toString()); s = "HTTP/123.4567"; version = (HttpVersion) BasicLineParser.parseProtocolVersion(s, null); Assert.assertEquals("HTTP protocol name", "HTTP", version.getProtocol()); Assert.assertEquals("HTTP major version number", 123, version.getMajor()); Assert.assertEquals("HTTP minor version number", 4567, version.getMinor()); Assert.assertEquals("HTTP version number", s, version.toString()); } @Test public void testHttpVersionParsingUsingCursor() throws Exception { String s = "HTTP/1.1"; CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append(s); ParserCursor cursor = new ParserCursor(0, s.length()); final LineParser parser = BasicLineParser.INSTANCE; HttpVersion version = (HttpVersion) parser.parseProtocolVersion(buffer, cursor); Assert.assertEquals("HTTP protocol name", "HTTP", version.getProtocol()); Assert.assertEquals("HTTP major version number", 1, version.getMajor()); Assert.assertEquals("HTTP minor version number", 1, version.getMinor()); Assert.assertEquals("HTTP version number", "HTTP/1.1", version.toString()); Assert.assertEquals(s.length(), cursor.getPos()); Assert.assertTrue(cursor.atEnd()); s = "HTTP/1.123 123"; buffer = new CharArrayBuffer(16); buffer.append(s); cursor = new ParserCursor(0, s.length()); version = (HttpVersion) parser.parseProtocolVersion(buffer, cursor); Assert.assertEquals("HTTP protocol name", "HTTP", version.getProtocol()); Assert.assertEquals("HTTP major version number", 1, version.getMajor()); Assert.assertEquals("HTTP minor version number", 123, version.getMinor()); Assert.assertEquals("HTTP version number", "HTTP/1.123", version.toString()); Assert.assertEquals(' ', buffer.charAt(cursor.getPos())); Assert.assertEquals(s.length() - 4, cursor.getPos()); Assert.assertFalse(cursor.atEnd()); } @Test public void testInvalidHttpVersionParsing() throws Exception { try { BasicLineParser.parseProtocolVersion((String)null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { //expected } try { BasicLineParser.parseProtocolVersion (" ", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } try { BasicLineParser.parseProtocolVersion ("HTT", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } try { BasicLineParser.parseProtocolVersion ("crap", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } try { BasicLineParser.parseProtocolVersion ("HTTP/crap", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } try { BasicLineParser.parseProtocolVersion ("HTTP/1", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } try { BasicLineParser.parseProtocolVersion ("HTTP/1234 ", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } try { BasicLineParser.parseProtocolVersion ("HTTP/1.", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } try { BasicLineParser.parseProtocolVersion ("HTTP/whatever.whatever whatever", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } try { BasicLineParser.parseProtocolVersion ("HTTP/1.whatever whatever", null); Assert.fail("ParseException should have been thrown"); } catch (final ParseException e) { //expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestHeaderGroup.java0100644 0000000 0000000 00000022026 12276755422 031142 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link HeaderGroup}. * */ public class TestHeaderGroup { @Test public void testConstructor() { final HeaderGroup headergroup = new HeaderGroup(); Assert.assertNotNull(headergroup.getAllHeaders()); Assert.assertEquals(0, headergroup.getAllHeaders().length); } @Test public void testClear() { final HeaderGroup headergroup = new HeaderGroup(); headergroup.addHeader(new BasicHeader("name", "value")); Assert.assertEquals(1, headergroup.getAllHeaders().length); headergroup.clear(); Assert.assertEquals(0, headergroup.getAllHeaders().length); } @Test public void testAddRemoveHeader() { final HeaderGroup headergroup = new HeaderGroup(); final Header header = new BasicHeader("name", "value"); headergroup.addHeader(header); headergroup.addHeader(null); Assert.assertEquals(1, headergroup.getAllHeaders().length); headergroup.removeHeader(header); headergroup.removeHeader(null); Assert.assertEquals(0, headergroup.getAllHeaders().length); } @Test public void testUpdateHeader() { final HeaderGroup headergroup = new HeaderGroup(); final Header header1 = new BasicHeader("name1", "value1"); final Header header2 = new BasicHeader("name2", "value2"); final Header header3 = new BasicHeader("name3", "value3"); headergroup.addHeader(header1); headergroup.addHeader(header2); headergroup.addHeader(header3); headergroup.updateHeader(new BasicHeader("name2", "newvalue")); headergroup.updateHeader(new BasicHeader("name4", "value4")); headergroup.updateHeader(null); Assert.assertEquals(4, headergroup.getAllHeaders().length); Assert.assertEquals("newvalue", headergroup.getFirstHeader("name2").getValue()); } @Test public void testSetHeaders() { final HeaderGroup headergroup = new HeaderGroup(); final Header header1 = new BasicHeader("name1", "value1"); final Header header2 = new BasicHeader("name2", "value2"); final Header header3 = new BasicHeader("name3", "value3"); headergroup.addHeader(header1); headergroup.setHeaders(new Header[] { header2, header3 }); Assert.assertEquals(2, headergroup.getAllHeaders().length); Assert.assertEquals(0, headergroup.getHeaders("name1").length); Assert.assertFalse(headergroup.containsHeader("name1")); Assert.assertEquals(1, headergroup.getHeaders("name2").length); Assert.assertTrue(headergroup.containsHeader("name2")); Assert.assertEquals(1, headergroup.getHeaders("name3").length); Assert.assertTrue(headergroup.containsHeader("name3")); headergroup.setHeaders(null); Assert.assertEquals(0, headergroup.getAllHeaders().length); } @Test public void testFirstLastHeaders() { final HeaderGroup headergroup = new HeaderGroup(); final Header header1 = new BasicHeader("name", "value1"); final Header header2 = new BasicHeader("name", "value2"); final Header header3 = new BasicHeader("name", "value3"); headergroup.setHeaders(new Header[] { header1, header2, header3 }); Assert.assertNull(headergroup.getFirstHeader("whatever")); Assert.assertNull(headergroup.getLastHeader("whatever")); Assert.assertEquals("value1", headergroup.getFirstHeader("name").getValue()); Assert.assertEquals("value3", headergroup.getLastHeader("name").getValue()); } @Test public void testCondensedHeader() { final HeaderGroup headergroup = new HeaderGroup(); Assert.assertNull(headergroup.getCondensedHeader("name")); final Header header1 = new BasicHeader("name", "value1"); final Header header2 = new BasicHeader("name", "value2"); final Header header3 = new BasicHeader("name", "value3"); headergroup.setHeaders(new Header[] { header1, header2, header3 }); Assert.assertEquals("value1, value2, value3", headergroup.getCondensedHeader("name").getValue()); headergroup.setHeaders(new Header[] { header1 }); Assert.assertEquals(header1, headergroup.getCondensedHeader("name")); } @Test public void testIterator() { final HeaderGroup headergroup = new HeaderGroup(); final HeaderIterator i = headergroup.iterator(); Assert.assertNotNull(i); Assert.assertFalse(i.hasNext()); } @Test public void testHeaderRemove() { final HeaderGroup headergroup = new HeaderGroup(); final Header header1 = new BasicHeader("name", "value1"); final Header header2 = new BasicHeader("name", "value2"); final Header header3 = new BasicHeader("name", "value3"); headergroup.setHeaders(new Header[] { header1, header2, header3 }); final HeaderIterator i = headergroup.iterator(); Assert.assertNotNull(i); Assert.assertTrue(i.hasNext()); i.next(); Assert.assertTrue(i.hasNext()); i.next(); i.remove(); Assert.assertEquals(2, headergroup.getAllHeaders().length); Assert.assertTrue(i.hasNext()); i.next(); i.remove(); Assert.assertEquals(1, headergroup.getAllHeaders().length); Assert.assertFalse(i.hasNext()); } @Test public void testCloning() throws Exception { final HeaderGroup orig = new HeaderGroup(); final Header header1 = new BasicHeader("name", "value1"); final Header header2 = new BasicHeader("name", "value2"); final Header header3 = new BasicHeader("name", "value3"); orig.setHeaders(new Header[] { header1, header2, header3 }); final HeaderGroup clone = (HeaderGroup) orig.clone(); final Header[] headers1 = orig.getAllHeaders(); final Header[] headers2 = clone.getAllHeaders(); Assert.assertNotNull(headers1); Assert.assertNotNull(headers2); Assert.assertEquals(3, headers2.length); Assert.assertEquals(headers1.length, headers2.length); for (int i = 0; i < headers1.length; i++) { Assert.assertEquals(headers1[i].getName(), headers2[i].getName()); Assert.assertEquals(headers1[i].getValue(), headers2[i].getValue()); } } @Test public void testSerialization() throws Exception { final HeaderGroup orig = new HeaderGroup(); final Header header1 = new BasicHeader("name", "value1"); final Header header2 = new BasicHeader("name", "value2"); final Header header3 = new BasicHeader("name", "value3"); orig.setHeaders(new Header[] { header1, header2, header3 }); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final HeaderGroup clone = (HeaderGroup) instream.readObject(); final Header[] headers1 = orig.getAllHeaders(); final Header[] headers2 = clone.getAllHeaders(); Assert.assertNotNull(headers1); Assert.assertNotNull(headers2); Assert.assertEquals(headers1.length, headers2.length); for (int i = 0; i < headers1.length; i++) { Assert.assertEquals(headers1[i].getName(), headers2[i].getName()); Assert.assertEquals(headers1[i].getValue(), headers2[i].getValue()); } } } ././@LongLink0100644 0000000 0000000 00000000145 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicLineFormatter.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicLineFormatter.java0100644 0000000 0000000 00000013242 12276755422 032452 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.RequestLine; import org.apache.http.StatusLine; import org.apache.http.util.CharArrayBuffer; import org.junit.Assert; import org.junit.Test; /** * Tests for {@link BasicLineFormatter}. */ public class TestBasicLineFormatter { @Test public void testHttpVersionFormatting() throws Exception { final String s = BasicLineFormatter.formatProtocolVersion (HttpVersion.HTTP_1_1, null); Assert.assertEquals("HTTP/1.1", s); } @Test public void testHttpVersionFormattingInvalidInput() throws Exception { try { BasicLineFormatter.formatProtocolVersion (null, BasicLineFormatter.INSTANCE); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { BasicLineFormatter.INSTANCE.appendProtocolVersion (new CharArrayBuffer(10), (HttpVersion) null); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testRLFormatting() throws Exception { final RequestLine requestline = new BasicRequestLine("GET", "/stuff", HttpVersion.HTTP_1_1); final String s = BasicLineFormatter.formatRequestLine(requestline, null); Assert.assertEquals("GET /stuff HTTP/1.1", s); } @Test public void testRLFormattingInvalidInput() throws Exception { try { BasicLineFormatter.formatRequestLine (null, BasicLineFormatter.INSTANCE); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { BasicLineFormatter.INSTANCE.formatRequestLine (new CharArrayBuffer(10), (RequestLine) null); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testSLFormatting() throws Exception { StatusLine statusline = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); String s = BasicLineFormatter.formatStatusLine(statusline, null); Assert.assertEquals("HTTP/1.1 200 OK", s); statusline = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null); s = BasicLineFormatter.formatStatusLine(statusline, null); Assert.assertEquals("HTTP/1.1 200 ", s); // see "testSLParseSuccess" in TestBasicLineParser: // trailing space is correct } @Test public void testSLFormattingInvalidInput() throws Exception { try { BasicLineFormatter.formatStatusLine (null, BasicLineFormatter.INSTANCE); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { BasicLineFormatter.INSTANCE.formatStatusLine (new CharArrayBuffer(10), (StatusLine) null); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testHeaderFormatting() throws Exception { final Header header1 = new BasicHeader("name", "value"); String s = BasicLineFormatter.formatHeader(header1, null); Assert.assertEquals("name: value", s); final Header header2 = new BasicHeader("name", null); s = BasicLineFormatter.formatHeader(header2, null); Assert.assertEquals("name: ", s); } @Test public void testHeaderFormattingInvalidInput() throws Exception { try { BasicLineFormatter.formatHeader (null, BasicLineFormatter.INSTANCE); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { BasicLineFormatter.INSTANCE.formatHeader (new CharArrayBuffer(10), (Header) null); Assert.fail("IllegalArgumentException should habe been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestNameValuePair.java0100644 0000000 0000000 00000006712 12276755422 031432 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.NameValuePair; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link NameValuePair}. * */ public class TestNameValuePair { @Test public void testConstructor() { final NameValuePair param = new BasicNameValuePair("name", "value"); Assert.assertEquals("name", param.getName()); Assert.assertEquals("value", param.getValue()); } @Test public void testInvalidName() { try { new BasicNameValuePair(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { //expected } } @Test public void testHashCode() { final NameValuePair param1 = new BasicNameValuePair("name1", "value1"); final NameValuePair param2 = new BasicNameValuePair("name2", "value2"); final NameValuePair param3 = new BasicNameValuePair("name1", "value1"); Assert.assertTrue(param1.hashCode() != param2.hashCode()); Assert.assertTrue(param1.hashCode() == param3.hashCode()); } @Test public void testEquals() { final NameValuePair param1 = new BasicNameValuePair("name1", "value1"); final NameValuePair param2 = new BasicNameValuePair("name2", "value2"); final NameValuePair param3 = new BasicNameValuePair("name1", "value1"); Assert.assertFalse(param1.equals(param2)); Assert.assertFalse(param1.equals(null)); Assert.assertFalse(param1.equals("name1 = value1")); Assert.assertTrue(param1.equals(param1)); Assert.assertTrue(param2.equals(param2)); Assert.assertTrue(param1.equals(param3)); } @Test public void testToString() { final NameValuePair param1 = new BasicNameValuePair("name1", "value1"); Assert.assertEquals("name1=value1", param1.toString()); final NameValuePair param2 = new BasicNameValuePair("name1", null); Assert.assertEquals("name1", param2.toString()); } @Test public void testCloning() throws Exception { final BasicNameValuePair orig = new BasicNameValuePair("name1", "value1"); final BasicNameValuePair clone = (BasicNameValuePair) orig.clone(); Assert.assertEquals(orig, clone); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestStatusLine.java0100644 0000000 0000000 00000010402 12276755422 031023 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.junit.Assert; import org.junit.Test; /** * Simple tests for {@link StatusLine}. */ public class TestStatusLine { @Test public void testConstructor() { final StatusLine statusline = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); Assert.assertEquals(HttpVersion.HTTP_1_1, statusline.getProtocolVersion()); Assert.assertEquals(HttpStatus.SC_OK, statusline.getStatusCode()); Assert.assertEquals("OK", statusline.getReasonPhrase()); } @Test public void testConstructorInvalidInput() { try { new BasicStatusLine(null, HttpStatus.SC_OK, "OK"); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { /* expected */ } try { new BasicStatusLine(HttpVersion.HTTP_1_1, -1, "OK"); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { /* expected */ } } @Test public void testToString() throws Exception { StatusLine statusline = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); Assert.assertEquals("HTTP/1.1 200 OK", statusline.toString()); statusline = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null); // toString uses default formatting, hence the trailing space Assert.assertEquals("HTTP/1.1 200 ", statusline.toString()); } @Test public void testCloning() throws Exception { final BasicStatusLine orig = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicStatusLine clone = (BasicStatusLine) orig.clone(); Assert.assertEquals(orig.getReasonPhrase(), clone.getReasonPhrase()); Assert.assertEquals(orig.getStatusCode(), clone.getStatusCode()); Assert.assertEquals(orig.getProtocolVersion(), clone.getProtocolVersion()); } @Test public void testSerialization() throws Exception { final BasicStatusLine orig = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final BasicStatusLine clone = (BasicStatusLine) instream.readObject(); Assert.assertEquals(orig.getReasonPhrase(), clone.getReasonPhrase()); Assert.assertEquals(orig.getStatusCode(), clone.getStatusCode()); Assert.assertEquals(orig.getProtocolVersion(), clone.getProtocolVersion()); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBufferedHeader.java0100644 0000000 0000000 00000010507 12276755422 031571 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.http.HeaderElement; import org.apache.http.util.CharArrayBuffer; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link BufferedHeader}. * */ public class TestBufferedHeader { @Test public void testBasicConstructor() { final CharArrayBuffer buf = new CharArrayBuffer(32); buf.append("name: value"); final BufferedHeader header = new BufferedHeader(buf); Assert.assertEquals("name", header.getName()); Assert.assertEquals("value", header.getValue()); Assert.assertSame(buf, header.getBuffer()); Assert.assertEquals(5, header.getValuePos()); } @Test public void testInvalidName() { try { new BufferedHeader(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { //expected } } @Test public void testHeaderElements() { final CharArrayBuffer buf = new CharArrayBuffer(32); buf.append("name: element1 = value1, element2; param1 = value1, element3"); final BufferedHeader header = new BufferedHeader(buf); final HeaderElement[] elements = header.getElements(); Assert.assertNotNull(elements); Assert.assertEquals(3, elements.length); Assert.assertEquals("element1", elements[0].getName()); Assert.assertEquals("value1", elements[0].getValue()); Assert.assertEquals("element2", elements[1].getName()); Assert.assertEquals(null, elements[1].getValue()); Assert.assertEquals("element3", elements[2].getName()); Assert.assertEquals(null, elements[2].getValue()); Assert.assertEquals(1, elements[1].getParameters().length); } @Test public void testCloning() throws Exception { final CharArrayBuffer buf = new CharArrayBuffer(32); buf.append("name: value"); final BufferedHeader orig = new BufferedHeader(buf); final BufferedHeader clone = (BufferedHeader) orig.clone(); Assert.assertEquals(orig.getName(), clone.getName()); Assert.assertEquals(orig.getValue(), clone.getValue()); } @Test public void testSerialization() throws Exception { final CharArrayBuffer buf = new CharArrayBuffer(32); buf.append("name: value"); final BufferedHeader orig = new BufferedHeader(buf); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final BufferedHeader clone = (BufferedHeader) instream.readObject(); Assert.assertEquals(orig.getName(), clone.getName()); Assert.assertEquals(orig.getValue(), clone.getValue()); } } ././@LongLink0100644 0000000 0000000 00000000155 12276757361 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderElementIterator.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderElementItera0100644 0000000 0000000 00000011366 12276755422 032453 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.util.NoSuchElementException; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HeaderElementIterator; import org.junit.Assert; import org.junit.Test; /** * Tests for {@link BasicHeaderElementIterator}. * */ public class TestBasicHeaderElementIterator { @Test public void testMultiHeader() { final Header[] headers = new Header[]{ new BasicHeader("Name", "value0"), new BasicHeader("Name", "value1") }; final HeaderElementIterator hei = new BasicHeaderElementIterator( new BasicHeaderIterator(headers, "Name")); Assert.assertTrue(hei.hasNext()); HeaderElement elem = hei.nextElement(); Assert.assertEquals("The two header values must be equal", "value0", elem.getName()); Assert.assertTrue(hei.hasNext()); elem = hei.nextElement(); Assert.assertEquals("The two header values must be equal", "value1", elem.getName()); Assert.assertFalse(hei.hasNext()); try { hei.next(); Assert.fail("NoSuchElementException should have been thrown"); } catch (final NoSuchElementException ex) { // expected } Assert.assertFalse(hei.hasNext()); try { hei.next(); Assert.fail("NoSuchElementException should have been thrown"); } catch (final NoSuchElementException ex) { // expected } } @Test public void testMultiHeaderSameLine() { final Header[] headers = new Header[]{ new BasicHeader("name", "value0,value1"), new BasicHeader("nAme", "cookie1=1,cookie2=2") }; final HeaderElementIterator hei = new BasicHeaderElementIterator(new BasicHeaderIterator(headers, "Name")); HeaderElement elem = hei.nextElement(); Assert.assertEquals("The two header values must be equal", "value0", elem.getName()); elem = hei.nextElement(); Assert.assertEquals("The two header values must be equal", "value1", elem.getName()); elem = hei.nextElement(); Assert.assertEquals("The two header values must be equal", "cookie1", elem.getName()); Assert.assertEquals("The two header values must be equal", "1", elem.getValue()); elem = hei.nextElement(); Assert.assertEquals("The two header values must be equal", "cookie2", elem.getName()); Assert.assertEquals("The two header values must be equal", "2", elem.getValue()); } @Test public void testFringeCases() { final Header[] headers = new Header[]{ new BasicHeader("Name", null), new BasicHeader("Name", " "), new BasicHeader("Name", ",,,") }; final HeaderElementIterator hei = new BasicHeaderElementIterator( new BasicHeaderIterator(headers, "Name")); Assert.assertFalse(hei.hasNext()); try { hei.next(); Assert.fail("NoSuchElementException should have been thrown"); } catch (final NoSuchElementException ex) { // expected } Assert.assertFalse(hei.hasNext()); try { hei.next(); Assert.fail("NoSuchElementException should have been thrown"); } catch (final NoSuchElementException ex) { // expected } } } ././@LongLink0100644 0000000 0000000 00000000146 12276757361 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderIterator.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderIterator.jav0100644 0000000 0000000 00000025425 12276755422 032446 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.util.NoSuchElementException; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.junit.Assert; import org.junit.Test; /** * Tests for {@link BasicHeaderIterator}. * */ public class TestBasicHeaderIterator { @Test public void testAllSame() { final Header[] headers = new Header[]{ new BasicHeader("Name", "value0"), new BasicHeader("nAme", "value1, value1.1"), new BasicHeader("naMe", "value2=whatever"), new BasicHeader("namE", "value3;tag=nil"), }; // without filter HeaderIterator hit = new BasicHeaderIterator(headers, null); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("0", headers[0], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("1", headers[1], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("2", headers[2], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("3", headers[3], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); // with filter hit = new BasicHeaderIterator(headers, "name"); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("0", headers[0], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("1", headers[1], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("2", headers[2], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("3", headers[3], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); } @Test public void testFirstLastOneNone() { final Header[] headers = new Header[]{ new BasicHeader("match" , "value0"), new BasicHeader("mismatch", "value1, value1.1"), new BasicHeader("single" , "value2=whatever"), new BasicHeader("match" , "value3;tag=nil"), }; // without filter HeaderIterator hit = new BasicHeaderIterator(headers, null); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("0", headers[0], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("1", headers[1], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("2", headers[2], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("3", headers[3], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); // with filter, first & last hit = new BasicHeaderIterator(headers, "match"); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("0", headers[0], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("3", headers[3], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); // with filter, one match hit = new BasicHeaderIterator(headers, "single"); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("2", headers[2], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); // with filter, no match hit = new BasicHeaderIterator(headers, "way-off"); Assert.assertFalse(hit.hasNext()); } @Test public void testInterspersed() { final Header[] headers = new Header[]{ new BasicHeader("yellow", "00"), new BasicHeader("maroon", "01"), new BasicHeader("orange", "02"), new BasicHeader("orange", "03"), new BasicHeader("orange", "04"), new BasicHeader("yellow", "05"), new BasicHeader("maroon", "06"), new BasicHeader("maroon", "07"), new BasicHeader("maroon", "08"), new BasicHeader("yellow", "09"), new BasicHeader("maroon", "0a"), new BasicHeader("yellow", "0b"), new BasicHeader("orange", "0c"), new BasicHeader("yellow", "0d"), new BasicHeader("orange", "0e"), }; // without filter HeaderIterator hit = new BasicHeaderIterator(headers, null); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("0", headers[0], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("1", headers[1], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("2", headers[2], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("3", headers[3], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("4", headers[4], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("5", headers[5], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("6", headers[6], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("7", headers[7], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("8", headers[8], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("9", headers[9], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("a", headers[10], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("b", headers[11], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("c", headers[12], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("d", headers[13], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("e", headers[14], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); // yellow 0, 5, 9, 11, 13 hit = new BasicHeaderIterator(headers, "Yellow"); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("0", headers[0], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("5", headers[5], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("9", headers[9], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("b", headers[11], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("d", headers[13], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); // maroon 1, 6, 7, 8, 10 hit = new BasicHeaderIterator(headers, "marOOn"); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("1", headers[1], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("6", headers[6], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("7", headers[7], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("8", headers[8], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("a", headers[10], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); // orange 2, 3, 4, 12, 14 hit = new BasicHeaderIterator(headers, "OranGe"); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("2", headers[2], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("3", headers[3], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("4", headers[4], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("b", headers[12], hit.nextHeader()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("e", headers[14], hit.nextHeader()); Assert.assertFalse(hit.hasNext()); } @Test public void testInvalid() { HeaderIterator hit = null; try { hit = new BasicHeaderIterator(null, "whatever"); Assert.fail("null headers not detected"); } catch (final IllegalArgumentException iax) { // expected } // this is not invalid hit = new BasicHeaderIterator(new Header[0], "whatever"); Assert.assertFalse(hit.hasNext()); // but this is try { hit.nextHeader(); Assert.fail("next beyond end not detected"); } catch (final NoSuchElementException nsx) { // expected } } @Test public void testRemaining() { // to satisfy Clover and take coverage to 100% final Header[] headers = new Header[]{ new BasicHeader("Name", "value0"), new BasicHeader("nAme", "value1, value1.1"), new BasicHeader("naMe", "value2=whatever"), new BasicHeader("namE", "value3;tag=nil"), }; // without filter, using plain next() HeaderIterator hit = new BasicHeaderIterator(headers, null); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("0", headers[0], hit.next()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("1", headers[1], hit.next()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("2", headers[2], hit.next()); Assert.assertTrue(hit.hasNext()); Assert.assertEquals("3", headers[3], hit.next()); Assert.assertFalse(hit.hasNext()); hit = new BasicHeaderIterator(headers, null); Assert.assertTrue(hit.hasNext()); try { hit.remove(); Assert.fail("remove not detected"); } catch (final UnsupportedOperationException uox) { // expected } Assert.assertTrue("no next", ((BasicHeaderIterator)hit).findNext(-3) < 0); } } ././@LongLink0100644 0000000 0000000 00000000145 12276757361 011653 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicTokenIterator.javahttpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicTokenIterator.java0100644 0000000 0000000 00000026020 12276755422 032467 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import java.util.NoSuchElementException; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.ParseException; import org.apache.http.TokenIterator; import org.junit.Assert; import org.junit.Test; /** * Tests for {@link BasicTokenIterator}. * */ public class TestBasicTokenIterator { @Test public void testSingleHeader() { Header[] headers = new Header[]{ new BasicHeader("Name", "token0,token1, token2 , token3") }; HeaderIterator hit = new BasicHeaderIterator(headers, null); TokenIterator ti = new BasicTokenIterator(hit); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token0", "token0", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token1", "token1", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token2", "token2", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token3", "token3", ti.nextToken()); Assert.assertFalse(ti.hasNext()); headers = new Header[]{ new BasicHeader("Name", "token0") }; hit = new BasicHeaderIterator(headers, null); ti = new BasicTokenIterator(hit); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token0", "token0", ti.nextToken()); Assert.assertFalse(ti.hasNext()); } @Test public void testMultiHeader() { final Header[] headers = new Header[]{ new BasicHeader("Name", "token0,token1"), new BasicHeader("Name", ""), new BasicHeader("Name", "token2"), new BasicHeader("Name", " "), new BasicHeader("Name", "token3 "), new BasicHeader("Name", ","), new BasicHeader("Name", "token4"), }; final HeaderIterator hit = new BasicHeaderIterator(headers, null); final TokenIterator ti = new BasicTokenIterator(hit); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token0", "token0", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token1", "token1", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token2", "token2", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token3", "token3", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token4", "token4", ti.nextToken()); Assert.assertFalse(ti.hasNext()); } @Test public void testEmpty() { final Header[] headers = new Header[]{ new BasicHeader("Name", " "), new BasicHeader("Name", ""), new BasicHeader("Name", ","), new BasicHeader("Name", " ,, "), }; HeaderIterator hit = new BasicHeaderIterator(headers, null); TokenIterator ti = new BasicTokenIterator(hit); Assert.assertFalse(ti.hasNext()); hit = new BasicHeaderIterator(headers, "empty"); ti = new BasicTokenIterator(hit); Assert.assertFalse(ti.hasNext()); } @Test public void testValueStart() { final Header[] headers = new Header[]{ new BasicHeader("Name", "token0"), new BasicHeader("Name", " token1"), new BasicHeader("Name", ",token2"), new BasicHeader("Name", " ,token3"), new BasicHeader("Name", ", token4"), new BasicHeader("Name", " , token5"), }; final HeaderIterator hit = new BasicHeaderIterator(headers, null); final TokenIterator ti = new BasicTokenIterator(hit); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token0", "token0", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token1", "token1", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token2", "token2", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token3", "token3", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token4", "token4", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token5", "token5", ti.nextToken()); Assert.assertFalse(ti.hasNext()); } @Test public void testValueEnd() { final Header[] headers = new Header[]{ new BasicHeader("Name", "token0"), new BasicHeader("Name", "token1 "), new BasicHeader("Name", "token2,"), new BasicHeader("Name", "token3 ,"), new BasicHeader("Name", "token4, "), new BasicHeader("Name", "token5 , "), }; final HeaderIterator hit = new BasicHeaderIterator(headers, null); final TokenIterator ti = new BasicTokenIterator(hit); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token0", "token0", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token1", "token1", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token2", "token2", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token3", "token3", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token4", "token4", ti.nextToken()); Assert.assertTrue(ti.hasNext()); Assert.assertEquals("token5", "token5", ti.nextToken()); Assert.assertFalse(ti.hasNext()); } @Test public void testTokenChar() { final Header[] headers = new Header[]{ new BasicHeader("Name", "token0") }; final HeaderIterator hit = new BasicHeaderIterator(headers, null); final BasicTokenIterator bti = new BasicTokenIterator(hit); Assert.assertTrue ("letter" , bti.isTokenChar('j')); Assert.assertFalse("control" , bti.isTokenChar('\b')); Assert.assertFalse("separator", bti.isTokenChar('?')); Assert.assertTrue ("other" , bti.isTokenChar('-')); } @Test public void testInvalid() { final Header[] headers = new Header[]{ new BasicHeader("in", "token0=token1"), new BasicHeader("no", "token0 token1"), new BasicHeader("pre", ". * */ package org.apache.http.message; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.http.HttpVersion; import org.apache.http.RequestLine; import org.junit.Assert; import org.junit.Test; /** * Simple tests for {@link RequestLine}. */ public class TestRequestLine { @Test public void testConstructor() { final RequestLine requestline = new BasicRequestLine("GET", "/stuff", HttpVersion.HTTP_1_1); Assert.assertEquals("GET", requestline.getMethod()); Assert.assertEquals("/stuff", requestline.getUri()); Assert.assertEquals(HttpVersion.HTTP_1_1, requestline.getProtocolVersion()); } @Test public void testConstructorInvalidInput() { try { new BasicRequestLine(null, "/stuff", HttpVersion.HTTP_1_1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { /* expected */ } try { new BasicRequestLine("GET", null, HttpVersion.HTTP_1_1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { /* expected */ } try { new BasicRequestLine("GET", "/stuff", (HttpVersion)null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { /* expected */ } } @Test public void testCloning() throws Exception { final BasicRequestLine orig = new BasicRequestLine("GET", "/stuff", HttpVersion.HTTP_1_1); final BasicRequestLine clone = (BasicRequestLine) orig.clone(); Assert.assertEquals(orig.getMethod(), clone.getMethod()); Assert.assertEquals(orig.getUri(), clone.getUri()); Assert.assertEquals(orig.getProtocolVersion(), clone.getProtocolVersion()); } @Test public void testSerialization() throws Exception { final BasicRequestLine orig = new BasicRequestLine("GET", "/stuff", HttpVersion.HTTP_1_1); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final BasicRequestLine clone = (BasicRequestLine) instream.readObject(); Assert.assertEquals(orig.getMethod(), clone.getMethod()); Assert.assertEquals(orig.getUri(), clone.getUri()); Assert.assertEquals(orig.getProtocolVersion(), clone.getProtocolVersion()); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestBasicMessages.java0100644 0000000 0000000 00000016315 12276755422 031452 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.entity.BasicHttpEntity; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link org.apache.http.HttpMessage}. * */ public class TestBasicMessages { @Test public void testDefaultResponseConstructors() { HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_BAD_REQUEST, "Bad Request"); Assert.assertNotNull(response.getProtocolVersion()); Assert.assertEquals(HttpVersion.HTTP_1_0, response.getProtocolVersion()); Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); response = new BasicHttpResponse(new BasicStatusLine( HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "whatever")); Assert.assertNotNull(response.getProtocolVersion()); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion()); Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode()); Assert.assertEquals("whatever", response.getStatusLine().getReasonPhrase()); } @Test public void testSetResponseStatus() { HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Assert.assertNotNull(response.getProtocolVersion()); Assert.assertNotNull(response.getStatusLine()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_BAD_REQUEST, "Bad Request"); Assert.assertNotNull(response.getProtocolVersion()); Assert.assertEquals(HttpVersion.HTTP_1_0, response.getProtocolVersion()); Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); response = new BasicHttpResponse(new BasicStatusLine( HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "whatever")); Assert.assertNotNull(response.getProtocolVersion()); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion()); Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode()); Assert.assertEquals("whatever", response.getStatusLine().getReasonPhrase()); response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); try { response.setStatusCode(-23); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); try { response.setStatusLine(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testSetResponseEntity() { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); Assert.assertNull(response.getEntity()); final HttpEntity entity = new BasicHttpEntity(); response.setEntity(entity); Assert.assertTrue(entity == response.getEntity()); } @Test public void testDefaultRequestConstructors() { HttpRequest request = new BasicHttpRequest("WHATEVER", "/"); Assert.assertNotNull(request.getProtocolVersion()); Assert.assertEquals("WHATEVER", request.getRequestLine().getMethod()); Assert.assertEquals("/", request.getRequestLine().getUri()); request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_0); Assert.assertEquals(HttpVersion.HTTP_1_0, request.getProtocolVersion()); Assert.assertEquals("GET", request.getRequestLine().getMethod()); Assert.assertEquals("/", request.getRequestLine().getUri()); try { new BasicHttpRequest(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new BasicHttpRequest("GET", null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new BasicHttpRequest(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testDefaultEntityEnclosingRequestConstructors() { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", "/"); Assert.assertNotNull(request.getProtocolVersion()); Assert.assertEquals("GET", request.getRequestLine().getMethod()); Assert.assertEquals("/", request.getRequestLine().getUri()); request = new BasicHttpEntityEnclosingRequest("GET", "/", HttpVersion.HTTP_1_0); Assert.assertEquals(HttpVersion.HTTP_1_0, request.getProtocolVersion()); Assert.assertEquals("GET", request.getRequestLine().getMethod()); Assert.assertEquals("/", request.getRequestLine().getUri()); } @Test public void testSetRequestEntity() { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", "/"); Assert.assertNull(request.getEntity()); final HttpEntity entity = new BasicHttpEntity(); request.setEntity(entity); Assert.assertTrue(entity == request.getEntity()); } @Test public void testExpectContinue() { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", "/"); Assert.assertFalse(request.expectContinue()); request.addHeader("Expect", "100-Continue"); Assert.assertTrue(request.expectContinue()); } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestAbstractMessage.java0100644 0000000 0000000 00000011424 12276755422 032005 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.Header; import org.apache.http.HttpMessage; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link AbstractHttpMessage}. * */ public class TestAbstractMessage { static class TestHttpMessage extends AbstractHttpMessage { private final ProtocolVersion ver; public TestHttpMessage(final ProtocolVersion ver) { super(); this.ver = ver != null ? ver : HttpVersion.HTTP_1_1; } public TestHttpMessage() { this(HttpVersion.HTTP_1_1); } public ProtocolVersion getProtocolVersion() { return ver; } } @Test public void testBasicProperties() { final HttpMessage message = new TestHttpMessage(); Assert.assertNotNull(message.headerIterator()); final Header[] headers = message.getAllHeaders(); Assert.assertNotNull(headers); Assert.assertEquals(0, headers.length); } @Test public void testBasicHeaderOps() { final HttpMessage message = new TestHttpMessage(); Assert.assertFalse(message.containsHeader("whatever")); message.addHeader("name", "1"); message.addHeader("name", "2"); Header[] headers = message.getAllHeaders(); Assert.assertNotNull(headers); Assert.assertEquals(2, headers.length); Header h = message.getFirstHeader("name"); Assert.assertNotNull(h); Assert.assertEquals("1", h.getValue()); message.setHeader("name", "3"); h = message.getFirstHeader("name"); Assert.assertNotNull(h); Assert.assertEquals("3", h.getValue()); h = message.getLastHeader("name"); Assert.assertNotNull(h); Assert.assertEquals("2", h.getValue()); // Should have no effect message.addHeader(null); message.setHeader(null); headers = message.getHeaders("name"); Assert.assertNotNull(headers); Assert.assertEquals(2, headers.length); Assert.assertEquals("3", headers[0].getValue()); Assert.assertEquals("2", headers[1].getValue()); message.addHeader("name", "4"); headers[1] = new BasicHeader("name", "5"); message.setHeaders(headers); headers = message.getHeaders("name"); Assert.assertNotNull(headers); Assert.assertEquals(2, headers.length); Assert.assertEquals("3", headers[0].getValue()); Assert.assertEquals("5", headers[1].getValue()); message.setHeader("whatever", null); message.removeHeaders("name"); message.removeHeaders(null); headers = message.getAllHeaders(); Assert.assertNotNull(headers); Assert.assertEquals(1, headers.length); Assert.assertEquals(null, headers[0].getValue()); message.removeHeader(message.getFirstHeader("whatever")); headers = message.getAllHeaders(); Assert.assertNotNull(headers); Assert.assertEquals(0, headers.length); } @Test public void testInvalidInput() { final HttpMessage message = new TestHttpMessage(); try { message.addHeader(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { message.setHeader(null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } httpcomponents-core-4.3.2/httpcore/src/test/java/org/apache/http/message/TestHeaderElement.java0100644 0000000 0000000 00000015745 12276755422 031451 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.message; import org.apache.http.HeaderElement; import org.apache.http.NameValuePair; import org.junit.Assert; import org.junit.Test; /** * Simple tests for {@link HeaderElement}. */ public class TestHeaderElement { @Test public void testConstructor3() throws Exception { final HeaderElement element = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param1", "value1"), new BasicNameValuePair("param2", "value2") } ); Assert.assertEquals("name", element.getName()); Assert.assertEquals("value", element.getValue()); Assert.assertEquals(2, element.getParameters().length); Assert.assertEquals("value1", element.getParameterByName("param1").getValue()); Assert.assertEquals("value2", element.getParameterByName("param2").getValue()); } @Test public void testConstructor2() throws Exception { final HeaderElement element = new BasicHeaderElement("name", "value"); Assert.assertEquals("name", element.getName()); Assert.assertEquals("value", element.getValue()); Assert.assertEquals(0, element.getParameters().length); } @Test public void testInvalidName() { try { new BasicHeaderElement(null, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { //expected } } @Test public void testParamByName() throws Exception { final String s = "name = value; param1 = value1; param2 = value2"; final HeaderElement element = BasicHeaderValueParser.parseHeaderElement(s, null); Assert.assertEquals("value1", element.getParameterByName("param1").getValue()); Assert.assertEquals("value2", element.getParameterByName("param2").getValue()); Assert.assertNull(element.getParameterByName("param3")); try { element.getParameterByName(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { //expected } } @Test public void testHashCode() { final HeaderElement element1 = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param1", "value1"), new BasicNameValuePair("param2", "value2") } ); final HeaderElement element2 = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param2", "value2"), new BasicNameValuePair("param1", "value1") } ); final HeaderElement element3 = new BasicHeaderElement("name", "value"); final HeaderElement element4 = new BasicHeaderElement("name", "value"); final HeaderElement element5 = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param1", "value1"), new BasicNameValuePair("param2", "value2") } ); Assert.assertTrue(element1.hashCode() != element2.hashCode()); Assert.assertTrue(element1.hashCode() != element3.hashCode()); Assert.assertTrue(element2.hashCode() != element3.hashCode()); Assert.assertTrue(element3.hashCode() == element4.hashCode()); Assert.assertTrue(element1.hashCode() == element5.hashCode()); } @Test public void testEquals() { final HeaderElement element1 = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param1", "value1"), new BasicNameValuePair("param2", "value2") } ); final HeaderElement element2 = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param2", "value2"), new BasicNameValuePair("param1", "value1") } ); final HeaderElement element3 = new BasicHeaderElement("name", "value"); final HeaderElement element4 = new BasicHeaderElement("name", "value"); final HeaderElement element5 = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param1", "value1"), new BasicNameValuePair("param2", "value2") } ); Assert.assertTrue(element1.equals(element1)); Assert.assertTrue(!element1.equals(element2)); Assert.assertTrue(!element1.equals(element3)); Assert.assertTrue(!element2.equals(element3)); Assert.assertTrue(element3.equals(element4)); Assert.assertTrue(element1.equals(element5)); Assert.assertFalse(element1.equals(null)); Assert.assertFalse(element1.equals("name = value; param1 = value1; param2 = value2")); } @Test public void testToString() { String s = "name=value; param1=value1; param2=value2"; HeaderElement element = BasicHeaderValueParser.parseHeaderElement(s, null); Assert.assertEquals(s, element.toString()); s = "name; param1=value1; param2=value2"; element = BasicHeaderValueParser.parseHeaderElement(s, null); Assert.assertEquals(s, element.toString()); } @Test public void testCloning() throws Exception { final BasicHeaderElement orig = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param1", "value1"), new BasicNameValuePair("param2", "value2") } ); final BasicHeaderElement clone = (BasicHeaderElement) orig.clone(); Assert.assertEquals(orig, clone); } } httpcomponents-core-4.3.2/httpcore/src/examples/0040755 0000000 0000000 00000000000 12276755417 020542 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/examples/org/0040755 0000000 0000000 00000000000 12276755417 021331 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/examples/org/apache/0040755 0000000 0000000 00000000000 12276755417 022552 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/examples/org/apache/http/0040755 0000000 0000000 00000000000 12276755417 023531 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore/src/examples/org/apache/http/examples/0040755 0000000 0000000 00000000000 12276755417 025347 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000146 12276757361 011654 Lustar 0000000 0000000 httpcomponents-core-4.3.2/httpcore/src/examples/org/apache/http/examples/ElementalPoolingHttpGet.javahttpcomponents-core-4.3.2/httpcore/src/examples/org/apache/http/examples/ElementalPoolingHttpGet.jav0100644 0000000 0000000 00000013100 12276755417 032577 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.examples; import java.io.IOException; import java.util.concurrent.Future; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpClientConnection; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.pool.BasicConnFactory; import org.apache.http.impl.pool.BasicConnPool; import org.apache.http.impl.pool.BasicPoolEntry; import org.apache.http.message.BasicHttpRequest; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Elemental example for executing multiple GET requests from different threads using a connection * pool. */ public class ElementalPoolingHttpGet { public static void main(String[] args) throws Exception { final HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new RequestContent()) .add(new RequestTargetHost()) .add(new RequestConnControl()) .add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); final HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); final BasicConnPool pool = new BasicConnPool(new BasicConnFactory()); pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(2); HttpHost[] targets = { new HttpHost("www.google.com", 80), new HttpHost("www.yahoo.com", 80), new HttpHost("www.apache.com", 80) }; class WorkerThread extends Thread { private final HttpHost target; WorkerThread(final HttpHost target) { super(); this.target = target; } @Override public void run() { ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try { Future future = pool.lease(this.target, null); boolean reusable = false; BasicPoolEntry entry = future.get(); try { HttpClientConnection conn = entry.getConnection(); HttpCoreContext coreContext = HttpCoreContext.create(); coreContext.setTargetHost(this.target); BasicHttpRequest request = new BasicHttpRequest("GET", "/"); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); httpexecutor.preProcess(request, httpproc, coreContext); HttpResponse response = httpexecutor.execute(request, conn, coreContext); httpexecutor.postProcess(response, httpproc, coreContext); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); reusable = connStrategy.keepAlive(response, coreContext); } catch (IOException ex) { throw ex; } catch (HttpException ex) { throw ex; } finally { if (reusable) { System.out.println("Connection kept alive..."); } pool.release(entry, reusable); } } catch (Exception ex) { System.out.println("Request to " + this.target + " failed: " + ex.getMessage()); } } }; WorkerThread[] workers = new WorkerThread[targets.length]; for (int i = 0; i < workers.length; i++) { workers[i] = new WorkerThread(targets[i]); } for (int i = 0; i < workers.length; i++) { workers[i].start(); } for (int i = 0; i < workers.length; i++) { workers[i].join(); } } } httpcomponents-core-4.3.2/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java0100644 0000000 0000000 00000024345 12276755417 032154 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.examples; import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.security.KeyStore; import java.util.Locale; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.DefaultBHttpServerConnection; import org.apache.http.impl.DefaultBHttpServerConnectionFactory; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.UriHttpRequestHandlerMapper; import org.apache.http.util.EntityUtils; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; /** * Basic, yet fully functional and spec compliant, HTTP/1.1 file server. */ public class ElementalHttpServer { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1); } // Document root directory String docRoot = args[0]; int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new ResponseDate()) .add(new ResponseServer("Test/1.1")) .add(new ResponseContent()) .add(new ResponseConnControl()).build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = ElementalHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); } static class HttpFileHandler implements HttpRequestHandler { private final String docRoot; public HttpFileHandler(final String docRoot) { super(); this.docRoot = docRoot; } public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } String target = request.getRequestLine().getUri(); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); System.out.println("Incoming entity content (bytes): " + entityContent.length); } final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8")); if (!file.exists()) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); StringEntity entity = new StringEntity( "

    File" + file.getPath() + " not found

    ", ContentType.create("text/html", "UTF-8")); response.setEntity(entity); System.out.println("File " + file.getPath() + " not found"); } else if (!file.canRead() || file.isDirectory()) { response.setStatusCode(HttpStatus.SC_FORBIDDEN); StringEntity entity = new StringEntity( "

    Access denied

    ", ContentType.create("text/html", "UTF-8")); response.setEntity(entity); System.out.println("Cannot read file " + file.getPath()); } else { response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null)); response.setEntity(body); System.out.println("Serving file " + file.getPath()); } } } static class RequestListenerThread extends Thread { private final HttpConnectionFactory connFactory; private final ServerSocket serversocket; private final HttpService httpService; public RequestListenerThread( final int port, final HttpService httpService, final SSLServerSocketFactory sf) throws IOException { this.connFactory = DefaultBHttpServerConnectionFactory.INSTANCE; this.serversocket = sf != null ? sf.createServerSocket(port) : new ServerSocket(port); this.httpService = httpService; } @Override public void run() { System.out.println("Listening on port " + this.serversocket.getLocalPort()); while (!Thread.interrupted()) { try { // Set up HTTP connection Socket socket = this.serversocket.accept(); System.out.println("Incoming connection from " + socket.getInetAddress()); HttpServerConnection conn = this.connFactory.createConnection(socket); // Start worker thread Thread t = new WorkerThread(this.httpService, conn); t.setDaemon(true); t.start(); } catch (InterruptedIOException ex) { break; } catch (IOException e) { System.err.println("I/O error initialising connection thread: " + e.getMessage()); break; } } } } static class WorkerThread extends Thread { private final HttpService httpservice; private final HttpServerConnection conn; public WorkerThread( final HttpService httpservice, final HttpServerConnection conn) { super(); this.httpservice = httpservice; this.conn = conn; } @Override public void run() { System.out.println("New connection thread"); HttpContext context = new BasicHttpContext(null); try { while (!Thread.interrupted() && this.conn.isOpen()) { this.httpservice.handleRequest(this.conn, context); } } catch (ConnectionClosedException ex) { System.err.println("Client closed connection"); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } catch (HttpException ex) { System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage()); } finally { try { this.conn.shutdown(); } catch (IOException ignore) {} } } } } httpcomponents-core-4.3.2/httpcore/src/examples/org/apache/http/examples/PrintVersionInfo.java0100644 0000000 0000000 00000005507 12276755417 031474 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.examples; import org.apache.http.util.VersionInfo; /** * Prints version information for debugging purposes. * This can be used to verify that the correct versions of the * HttpComponent JARs are picked up from the classpath. * * */ public class PrintVersionInfo { /** A default list of module packages. */ private final static String[] MODULE_LIST = { "org.apache.http", // HttpCore "org.apache.http.nio", // HttpCore NIO "org.apache.http.client", // HttpClient }; /** * Prints version information. * * @param args command line arguments. Leave empty to print version * information for the default packages. Otherwise, pass * a list of packages for which to get version info. */ public static void main(String args[]) { String[] pckgs = (args.length > 0) ? args : MODULE_LIST; VersionInfo[] via = VersionInfo.loadVersionInfo(pckgs, null); System.out.println("version info for thread context classloader:"); for (int i=0; i. * */ package org.apache.http.examples; import java.io.ByteArrayInputStream; import java.net.Socket; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.DefaultBHttpClientConnection; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Elemental example for executing multiple POST requests sequentially. */ public class ElementalHttpPost { public static void main(String[] args) throws Exception { HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new RequestContent()) .add(new RequestTargetHost()) .add(new RequestConnControl()) .add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpCoreContext coreContext = HttpCoreContext.create(); HttpHost host = new HttpHost("localhost", 8080); coreContext.setTargetHost(host); DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try { HttpEntity[] requestBodies = { new StringEntity( "This is the first test request", ContentType.create("text/plain", Consts.UTF_8)), new ByteArrayEntity( "This is the second test request".getBytes("UTF-8"), ContentType.APPLICATION_OCTET_STREAM), new InputStreamEntity( new ByteArrayInputStream( "This is the third test request (will be chunked)" .getBytes("UTF-8")), ContentType.APPLICATION_OCTET_STREAM) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); httpexecutor.preProcess(request, httpproc, coreContext); HttpResponse response = httpexecutor.execute(request, conn, coreContext); httpexecutor.postProcess(response, httpproc, coreContext); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, coreContext)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } } } httpcomponents-core-4.3.2/httpcore/src/examples/org/apache/http/examples/ElementalReverseProxy.java0100644 0000000 0000000 00000027621 12276755417 032523 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.examples; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ServerSocket; import java.net.Socket; import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpClientConnection; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpServerConnection; import org.apache.http.impl.DefaultBHttpClientConnection; import org.apache.http.impl.DefaultBHttpServerConnection; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.UriHttpRequestHandlerMapper; /** * Elemental HTTP/1.1 reverse proxy. */ public class ElementalReverseProxy { private static final String HTTP_IN_CONN = "http.proxy.in-conn"; private static final String HTTP_OUT_CONN = "http.proxy.out-conn"; private static final String HTTP_CONN_KEEPALIVE = "http.proxy.conn-keepalive"; public static void main(final String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specified target hostname and port"); System.exit(1); } final String hostname = args[0]; int port = 80; if (args.length > 1) { port = Integer.parseInt(args[1]); } final HttpHost target = new HttpHost(hostname, port); final Thread t = new RequestListenerThread(8888, target); t.setDaemon(false); t.start(); } static class ProxyHandler implements HttpRequestHandler { private final HttpHost target; private final HttpProcessor httpproc; private final HttpRequestExecutor httpexecutor; private final ConnectionReuseStrategy connStrategy; public ProxyHandler( final HttpHost target, final HttpProcessor httpproc, final HttpRequestExecutor httpexecutor) { super(); this.target = target; this.httpproc = httpproc; this.httpexecutor = httpexecutor; this.connStrategy = DefaultConnectionReuseStrategy.INSTANCE; } public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final HttpClientConnection conn = (HttpClientConnection) context.getAttribute( HTTP_OUT_CONN); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); // Remove hop-by-hop headers request.removeHeaders(HTTP.CONTENT_LEN); request.removeHeaders(HTTP.TRANSFER_ENCODING); request.removeHeaders(HTTP.CONN_DIRECTIVE); request.removeHeaders("Keep-Alive"); request.removeHeaders("Proxy-Authenticate"); request.removeHeaders("TE"); request.removeHeaders("Trailers"); request.removeHeaders("Upgrade"); this.httpexecutor.preProcess(request, this.httpproc, context); final HttpResponse targetResponse = this.httpexecutor.execute(request, conn, context); this.httpexecutor.postProcess(response, this.httpproc, context); // Remove hop-by-hop headers targetResponse.removeHeaders(HTTP.CONTENT_LEN); targetResponse.removeHeaders(HTTP.TRANSFER_ENCODING); targetResponse.removeHeaders(HTTP.CONN_DIRECTIVE); targetResponse.removeHeaders("Keep-Alive"); targetResponse.removeHeaders("TE"); targetResponse.removeHeaders("Trailers"); targetResponse.removeHeaders("Upgrade"); response.setStatusLine(targetResponse.getStatusLine()); response.setHeaders(targetResponse.getAllHeaders()); response.setEntity(targetResponse.getEntity()); System.out.println("<< Response: " + response.getStatusLine()); final boolean keepalive = this.connStrategy.keepAlive(response, context); context.setAttribute(HTTP_CONN_KEEPALIVE, new Boolean(keepalive)); } } static class RequestListenerThread extends Thread { private final HttpHost target; private final ServerSocket serversocket; private final HttpService httpService; public RequestListenerThread(final int port, final HttpHost target) throws IOException { this.target = target; this.serversocket = new ServerSocket(port); // Set up HTTP protocol processor for incoming connections final HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent("Test/1.1"), new RequestExpectContinue(true) }); // Set up HTTP protocol processor for outgoing connections final HttpProcessor outhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer("Test/1.1"), new ResponseContent(), new ResponseConnControl() }); // Set up outgoing request executor final HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); // Set up incoming request handler final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new ProxyHandler( this.target, outhttpproc, httpexecutor)); // Set up the HTTP service this.httpService = new HttpService(inhttpproc, reqistry); } @Override public void run() { System.out.println("Listening on port " + this.serversocket.getLocalPort()); while (!Thread.interrupted()) { try { final int bufsize = 8 * 1024; // Set up incoming HTTP connection final Socket insocket = this.serversocket.accept(); final DefaultBHttpServerConnection inconn = new DefaultBHttpServerConnection(bufsize); System.out.println("Incoming connection from " + insocket.getInetAddress()); inconn.bind(insocket); // Set up outgoing HTTP connection final Socket outsocket = new Socket(this.target.getHostName(), this.target.getPort()); final DefaultBHttpClientConnection outconn = new DefaultBHttpClientConnection(bufsize); outconn.bind(outsocket); System.out.println("Outgoing connection to " + outsocket.getInetAddress()); // Start worker thread final Thread t = new ProxyThread(this.httpService, inconn, outconn); t.setDaemon(true); t.start(); } catch (final InterruptedIOException ex) { break; } catch (final IOException e) { System.err.println("I/O error initialising connection thread: " + e.getMessage()); break; } } } } static class ProxyThread extends Thread { private final HttpService httpservice; private final HttpServerConnection inconn; private final HttpClientConnection outconn; public ProxyThread( final HttpService httpservice, final HttpServerConnection inconn, final HttpClientConnection outconn) { super(); this.httpservice = httpservice; this.inconn = inconn; this.outconn = outconn; } @Override public void run() { System.out.println("New connection thread"); final HttpContext context = new BasicHttpContext(null); // Bind connection objects to the execution context context.setAttribute(HTTP_IN_CONN, this.inconn); context.setAttribute(HTTP_OUT_CONN, this.outconn); try { while (!Thread.interrupted()) { if (!this.inconn.isOpen()) { this.outconn.close(); break; } this.httpservice.handleRequest(this.inconn, context); final Boolean keepalive = (Boolean) context.getAttribute(HTTP_CONN_KEEPALIVE); if (!Boolean.TRUE.equals(keepalive)) { this.outconn.close(); this.inconn.close(); break; } } } catch (final ConnectionClosedException ex) { System.err.println("Client closed connection"); } catch (final IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } catch (final HttpException ex) { System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage()); } finally { try { this.inconn.shutdown(); } catch (final IOException ignore) {} try { this.outconn.shutdown(); } catch (final IOException ignore) {} } } } } httpcomponents-core-4.3.2/httpcore/src/examples/org/apache/http/examples/ElementalHttpGet.java0100644 0000000 0000000 00000010247 12276755417 031421 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.examples; import java.net.Socket; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.impl.DefaultBHttpClientConnection; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.message.BasicHttpRequest; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Elemental example for executing multiple GET requests sequentially. */ public class ElementalHttpGet { public static void main(String[] args) throws Exception { HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new RequestContent()) .add(new RequestTargetHost()) .add(new RequestConnControl()) .add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpCoreContext coreContext = HttpCoreContext.create(); HttpHost host = new HttpHost("localhost", 8080); coreContext.setTargetHost(host); DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try { String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa"}; for (int i = 0; i < targets.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); httpexecutor.preProcess(request, httpproc, coreContext); HttpResponse response = httpexecutor.execute(request, conn, coreContext); httpexecutor.postProcess(response, httpproc, coreContext); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, coreContext)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } } } httpcomponents-core-4.3.2/httpcore-osgi/0040755 0000000 0000000 00000000000 12276755615 017074 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore-osgi/pom.xml0100644 0000000 0000000 00000007577 12276755416 020425 0ustar000000000 0000000 4.0.0 org.apache.httpcomponents httpcomponents-core 4.3.2 httpcore-osgi Apache HttpCore OSGi bundle 2005 HttpComponents Core (OSGi bundle) http://hc.apache.org/httpcomponents-core-ga bundle org.apache.httpcomponents httpcore ${project.version} org.apache.httpcomponents httpcore-nio ${project.version} org.apache.felix maven-bundle-plugin true Apache ${project.name} ${project.groupId}.httpcore <_exportcontents>org.apache.http.*;version=${project.version} *;scope=compile|runtime;inline=true org.codehaus.mojo clirr-maven-plugin true org.apache.httpcomponents.httpcore_${project.version} org.codehaus.mojo clirr-maven-plugin ${hc.clirr.version} true maven-project-info-reports-plugin ${hc.project-info.version} false dependencies dependency-info summary httpcomponents-core-4.3.2/httpcore-osgi/src/0040755 0000000 0000000 00000000000 12276755416 017662 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore-osgi/src/main/0040755 0000000 0000000 00000000000 12276755416 020606 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore-osgi/src/main/appended-resources/0040755 0000000 0000000 00000000000 12276755416 024376 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore-osgi/src/main/appended-resources/META-INF/0040755 0000000 0000000 00000000000 12276755416 025536 5ustar000000000 0000000 httpcomponents-core-4.3.2/httpcore-osgi/src/main/appended-resources/META-INF/NOTICE0100644 0000000 0000000 00000000210 12276755416 026430 0ustar000000000 0000000 This project contains annotations derived from JCIP-ANNOTATIONS Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net httpcomponents-core-4.3.2/httpcore-osgi/src/main/appended-resources/META-INF/LICENSE0100644 0000000 0000000 00000026564 12276755416 026555 0ustar000000000 0000000 ========================================================================= This project contains annotations in the package org.apache.http.annotation which are derived from JCIP-ANNOTATIONS Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net and the Creative Commons Attribution License (http://creativecommons.org/licenses/by/2.5) Full text: http://creativecommons.org/licenses/by/2.5/legalcode License THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 1. Definitions "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License. "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License. "Licensor" means the individual or entity that offers the Work under the terms of this License. "Original Author" means the individual or entity who created the Work. "Work" means the copyrightable work of authorship offered under the terms of this License. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. 2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws. 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; to create and reproduce Derivative Works; to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works; to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works. For the avoidance of doubt, where the work is a musical composition: Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work. Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions). Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions). The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved. 4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(b), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(b), as requested. If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit. 5. Representations, Warranties and Disclaimer UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. Termination This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 8. Miscellaneous Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. httpcomponents-core-4.3.2/src/0040755 0000000 0000000 00000000000 12276755416 015073 5ustar000000000 0000000 httpcomponents-core-4.3.2/src/docbkx/0040755 0000000 0000000 00000000000 12276755417 016346 5ustar000000000 0000000 httpcomponents-core-4.3.2/src/docbkx/nio-ext.xml0100644 0000000 0000000 00000313422 12276755417 020455 0ustar000000000 0000000 Asynchronous I/O based on NIO
    Differences from other I/O frameworks Solves similar problems as other frameworks, but has certain distinct features: minimalistic, optimized for data volume intensive protocols such as HTTP. efficient memory management: data consumer can read is only as much input data as it can process without having to allocate more memory. direct access to the NIO channels where possible.
    I/O reactor HttpCore NIO is based on the Reactor pattern as described by Doug Lea. The purpose of I/O reactors is to react to I/O events and to dispatch event notifications to individual I/O sessions. The main idea of I/O reactor pattern is to break away from the one thread per connection model imposed by the classic blocking I/O model. The IOReactor interface represents an abstract object which implements the Reactor pattern. Internally, IOReactor implementations encapsulate functionality of the NIO java.nio.channels.Selector. I/O reactors usually employ a small number of dispatch threads (often as few as one) to dispatch I/O event notifications to a much greater number (often as many as several thousands) of I/O sessions or connections. It is generally recommended to have one dispatch thread per CPU core.
    I/O dispatchers IOReactor implementations make use of the IOEventDispatch interface to notify clients of events pending for a particular session. All methods of the IOEventDispatch are executed on a dispatch thread of the I/O reactor. Therefore, it is important that processing that takes place in the event methods will not block the dispatch thread for too long, as the I/O reactor will be unable to react to other events. ioreactor.execute(eventDispatch); ]]> Generic I/O events as defined by the IOEventDispatch interface: <methodname>connected</methodname>: Triggered when a new session has been created. <methodname>inputReady</methodname>: Triggered when the session has pending input. <methodname>outputReady</methodname>: Triggered when the session is ready for output. <methodname>timeout</methodname>: Triggered when the session has timed out. <methodname>disconnected</methodname>: Triggered when the session has been terminated.
    I/O reactor shutdown The shutdown of I/O reactors is a complex process and may usually take a while to complete. I/O reactors will attempt to gracefully terminate all active I/O sessions and dispatch threads approximately within the specified grace period. If any of the I/O sessions fails to terminate correctly, the I/O reactor will forcibly shut down remaining sessions. long gracePeriod = 3000L; // milliseconds ioreactor.shutdown(gracePeriod); ]]> The IOReactor#shutdown(long) method is safe to call from any thread.
    I/O sessions The IOSession interface represents a sequence of logically related data exchanges between two end points. IOSession encapsulates functionality of NIO java.nio.channels.SelectionKey and java.nio.channels.SocketChannel. The channel associated with the IOSession can be used to read data from and write data to the session. ReadableByteChannel ch = (ReadableByteChannel) iosession.channel(); ByteBuffer dst = ByteBuffer.allocate(2048); ch.read(dst); ]]>
    I/O session state management I/O sessions are not bound to an execution thread, therefore one cannot use the context of the thread to store a session's state. All details about a particular session must be stored within the session itself. Object someState = <...> iosession.setAttribute("state", someState); ... IOSession iosession = <...> Object currentState = iosession.getAttribute("state"); ]]> Please note that if several sessions make use of shared objects, access to those objects must be made thread-safe.
    I/O session event mask One can declare an interest in a particular type of I/O events for a particular I/O session by setting its event mask. iosession.setEventMask(SelectionKey.OP_READ | SelectionKey.OP_WRITE); ]]> One can also toggle OP_READ and OP_WRITE flags individually. iosession.setEvent(SelectionKey.OP_READ); iosession.clearEvent(SelectionKey.OP_READ); ]]> Event notifications will not take place if the corresponding interest flag is not set.
    I/O session buffers Quite often I/O sessions need to maintain internal I/O buffers in order to transform input / output data prior to returning it to the consumer or writing it to the underlying channel. Memory management in HttpCore NIO is based on the fundamental principle that the data a consumer can read, is only as much input data as it can process without having to allocate more memory. That means, quite often some input data may remain unread in one of the internal or external session buffers. The I/O reactor can query the status of these session buffers, and make sure the consumer gets notified correctly as more data gets stored in one of the session buffers, thus allowing the consumer to read the remaining data once it is able to process it. I/O sessions can be made aware of the status of external session buffers using the SessionBufferStatus interface. SessionBufferStatus myBufferStatus = <...> iosession.setBufferStatus(myBufferStatus); iosession.hasBufferedInput(); iosession.hasBufferedOutput(); ]]>
    I/O session shutdown One can close an I/O session gracefully by calling IOSession#close() allowing the session to be closed in an orderly manner or by calling IOSession#shutdown() to forcibly close the underlying channel. The distinction between two methods is of primary importance for those types of I/O sessions that involve some sort of a session termination handshake such as SSL/TLS connections.
    Listening I/O reactors ListeningIOReactor represents an I/O reactor capable of listening for incoming connections on one or several ports. ListenerEndpoint ep1 = ioreactor.listen(new InetSocketAddress(8081) ); ListenerEndpoint ep2 = ioreactor.listen(new InetSocketAddress(8082)); ListenerEndpoint ep3 = ioreactor.listen(new InetSocketAddress(8083)); // Wait until all endpoints are up ep1.waitFor(); ep2.waitFor(); ep3.waitFor(); ]]> Once an endpoint is fully initialized it starts accepting incoming connections and propagates I/O activity notifications to the IOEventDispatch instance. One can obtain a set of registered endpoints at runtime, query the status of an endpoint at runtime, and close it if desired. Set eps = ioreactor.getEndpoints(); for (ListenerEndpoint ep: eps) { // Still active? System.out.println(ep.getAddress()); if (ep.isClosed()) { // If not, has it terminated due to an exception? if (ep.getException() != null) { ep.getException().printStackTrace(); } } else { ep.close(); } } ]]>
    Connecting I/O reactors ConnectingIOReactor represents an I/O reactor capable of establishing connections with remote hosts. SessionRequest sessionRequest = ioreactor.connect( new InetSocketAddress("www.google.com", 80), null, null, null); ]]> Opening a connection to a remote host usually tends to be a time consuming process and may take a while to complete. One can monitor and control the process of session initialization by means of the SessionRequestinterface. SessionRequest implementations are expected to be thread-safe. Session request can be aborted at any time by calling IOSession#cancel() from another thread of execution. One can pass several optional parameters to the ConnectingIOReactor#connect() method to exert a greater control over the process of session initialization. A non-null local socket address parameter can be used to bind the socket to a specific local address. SessionRequest sessionRequest = ioreactor.connect( new InetSocketAddress("www.google.com", 80), new InetSocketAddress("192.168.0.10", 1234), null, null); ]]> One can provide an attachment object, which will be added to the new session's context upon initialization. This object can be used to pass an initial processing state to the protocol handler. It is often desirable to be able to react to the completion of a session request asynchronously without having to wait for it, blocking the current thread of execution. One can optionally provide an implementation SessionRequestCallback interface to get notified of events related to session requests, such as request completion, cancellation, failure or timeout. SessionRequest sessionRequest = ioreactor.connect( new InetSocketAddress("www.google.com", 80), null, null, new SessionRequestCallback() { public void cancelled(SessionRequest request) { } public void completed(SessionRequest request) { System.out.println("new connection to " + request.getRemoteAddress()); } public void failed(SessionRequest request) { if (request.getException() != null) { request.getException().printStackTrace(); } } public void timeout(SessionRequest request) { } }); ]]>
    I/O reactor configuration I/O reactors by default use system dependent configuration which in most cases should be sensible enough. However in some cases custom settings may be necessary, for instance, in order to alter default socket properties and timeout values. One should rarely need to change other parameters.
    Queuing of I/O interest set operations Several older JRE implementations (primarily from IBM) include what Java API documentation refers to as a naive implementation of the java.nio.channels.SelectionKey class. The problem with java.nio.channels.SelectionKey in such JREs is that reading or writing of the I/O interest set may block indefinitely if the I/O selector is in the process of executing a select operation. HttpCore NIO can be configured to operate in a special mode wherein I/O interest set operations are queued and executed by on the dispatch thread only when the I/O selector is not engaged in a select operation.
    I/O reactor exception handling Protocol specific exceptions as well as those I/O exceptions thrown in the course of interaction with the session's channel are to be expected and are to be dealt with by specific protocol handlers. These exceptions may result in termination of an individual session but should not affect the I/O reactor and all other active sessions. There are situations, however, when the I/O reactor itself encounters an internal problem such as an I/O exception in the underlying NIO classes or an unhandled runtime exception. Those types of exceptions are usually fatal and will cause the I/O reactor to shut down automatically. There is a possibility to override this behavior and prevent I/O reactors from shutting down automatically in case of a runtime exception or an I/O exception in internal classes. This can be accomplished by providing a custom implementation of the IOReactorExceptionHandler interface. ioreactor.setExceptionHandler(new IOReactorExceptionHandler() { public boolean handle(IOException ex) { if (ex instanceof BindException) { // bind failures considered OK to ignore return true; } return false; } public boolean handle(RuntimeException ex) { if (ex instanceof UnsupportedOperationException) { // Unsupported operations considered OK to ignore return true; } return false; } }); ]]> One needs to be very careful about discarding exceptions indiscriminately. It is often much better to let the I/O reactor shut down itself cleanly and restart it rather than leaving it in an inconsistent or unstable state.
    I/O reactor audit log If an I/O reactor is unable to automatically recover from an I/O or a runtime exception it will enter the shutdown mode. First off, it will close all active listeners and cancel all pending new session requests. Then it will attempt to close all active I/O sessions gracefully giving them some time to flush pending output data and terminate cleanly. Lastly, it will forcibly shut down those I/O sessions that still remain active after the grace period. This is a fairly complex process, where many things can fail at the same time and many different exceptions can be thrown in the course of the shutdown process. The I/O reactor will record all exceptions thrown during the shutdown process, including the original one that actually caused the shutdown in the first place, in an audit log. One can examine the audit log and decide whether it is safe to restart the I/O reactor. // Give it 5 sec grace period ioreactor.shutdown(5000); List events = ioreactor.getAuditLog(); for (ExceptionEvent event: events) { System.err.println("Time: " + event.getTimestamp()); event.getCause().printStackTrace(); } ]]>
    Non-blocking HTTP connections Effectively non-blocking HTTP connections are wrappers around IOSession with HTTP specific functionality. Non-blocking HTTP connections are stateful and not thread-safe. Input / output operations on non-blocking HTTP connections should be restricted to the dispatch events triggered by the I/O event dispatch thread.
    Execution context of non-blocking HTTP connections Non-blocking HTTP connections are not bound to a particular thread of execution and therefore they need to maintain their own execution context. Each non-blocking HTTP connection has an HttpContext instance associated with it, which can be used to maintain a processing state. The HttpContext instance is thread-safe and can be manipulated from multiple threads. Object myStateObject = <...> HttpContext context = conn.getContext(); context.setAttribute("state", myStateObject); ]]>
    Working with non-blocking HTTP connections At any point of time one can obtain the request and response objects currently being transferred over the non-blocking HTTP connection. Any of these objects, or both, can be null if there is no incoming or outgoing message currently being transferred. HttpRequest request = conn.getHttpRequest(); if (request != null) { System.out.println("Transferring request: " + request.getRequestLine()); } HttpResponse response = conn.getHttpResponse(); if (response != null) { System.out.println("Transferring response: " + response.getStatusLine()); } ]]> However, please note that the current request and the current response may not necessarily represent the same message exchange! Non-blocking HTTP connections can operate in a full duplex mode. One can process incoming and outgoing messages completely independently from one another. This makes non-blocking HTTP connections fully pipelining capable, but at same time implies that this is the job of the protocol handler to match logically related request and the response messages. Over-simplified process of submitting a request on the client side may look like this: // Obtain execution context HttpContext context = conn.getContext(); // Obtain processing state Object state = context.getAttribute("state"); // Generate a request based on the state information HttpRequest request = new BasicHttpRequest("GET", "/"); conn.submitRequest(request); System.out.println(conn.isRequestSubmitted()); ]]> Over-simplified process of submitting a response on the server side may look like this: // Obtain execution context HttpContext context = conn.getContext(); // Obtain processing state Object state = context.getAttribute("state"); // Generate a response based on the state information HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentType("text/plain"); entity.setChunked(true); response.setEntity(entity); conn.submitResponse(response); System.out.println(conn.isResponseSubmitted()); ]]> Please note that one should rarely need to transmit messages using these low level methods and should use appropriate higher level HTTP service implementations instead.
    HTTP I/O control All non-blocking HTTP connections classes implement IOControl interface, which represents a subset of connection functionality for controlling interest in I/O even notifications. IOControl instances are expected to be fully thread-safe. Therefore IOControl can be used to request / suspend I/O event notifications from any thread. One must take special precautions when interacting with non-blocking connections. HttpRequest and HttpResponse are not thread-safe. It is generally advisable that all input / output operations on a non-blocking connection are executed from the I/O event dispatch thread. The following pattern is recommended: Use IOControl interface to pass control over connection's I/O events to another thread / session. If input / output operations need be executed on that particular connection, store all the required information (state) in the connection context and request the appropriate I/O operation by calling IOControl#requestInput() or IOControl#requestOutput() method. Execute the required operations from the event method on the dispatch thread using information stored in connection context. Please note all operations that take place in the event methods should not block for too long, because while the dispatch thread remains blocked in one session, it is unable to process events for all other sessions. I/O operations with the underlying channel of the session are not a problem as they are guaranteed to be non-blocking.
    Non-blocking content transfer The process of content transfer for non-blocking connections works completely differently compared to that of blocking connections, as non-blocking connections need to accommodate to the asynchronous nature of the NIO model. The main distinction between two types of connections is inability to use the usual, but inherently blocking java.io.InputStream and java.io.OutputStream classes to represent streams of inbound and outbound content. HttpCore NIO provides ContentEncoder and ContentDecoder interfaces to handle the process of asynchronous content transfer. Non-blocking HTTP connections will instantiate the appropriate implementation of a content codec based on properties of the entity enclosed with the message. Non-blocking HTTP connections will fire input events until the content entity is fully transferred. //Read data in ByteBuffer dst = ByteBuffer.allocate(2048); decoder.read(dst); // Decode will be marked as complete when // the content entity is fully transferred if (decoder.isCompleted()) { // Done } ]]> Non-blocking HTTP connections will fire output events until the content entity is marked as fully transferred. // Prepare output data ByteBuffer src = ByteBuffer.allocate(2048); // Write data out encoder.write(src); // Mark content entity as fully transferred when done encoder.complete(); ]]> Please note, one still has to provide an HttpEntity instance when submitting an entity enclosing message to the non-blocking HTTP connection. Properties of that entity will be used to initialize an ContentEncoder instance to be used for transferring entity content. Non-blocking HTTP connections, however, ignore inherently blocking HttpEntity#getContent() and HttpEntity#writeTo() methods of the enclosed entities. HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentType("text/plain"); entity.setChunked(true); entity.setContent(null); response.setEntity(entity); conn.submitResponse(response); ]]> Likewise, incoming entity enclosing message will have an HttpEntity instance associated with them, but an attempt to call HttpEntity#getContent() or HttpEntity#writeTo() methods will cause an java.lang.IllegalStateException. The HttpEntity instance can be used to determine properties of the incoming entity such as content length. HttpResponse response = conn.getHttpResponse(); HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(entity.getContentType()); System.out.println(entity.getContentLength()); System.out.println(entity.isChunked()); } ]]>
    Supported non-blocking content transfer mechanisms Default implementations of the non-blocking HTTP connection interfaces support three content transfer mechanisms defined by the HTTP/1.1 specification: <literal>Content-Length</literal> delimited: The end of the content entity is determined by the value of the Content-Length header. Maximum entity length: Long#MAX_VALUE. Identity coding: The end of the content entity is demarcated by closing the underlying connection (end of stream condition). For obvious reasons the identity encoding can only be used on the server side. Max entity length: unlimited. Chunk coding: The content is sent in small chunks. Max entity length: unlimited. The appropriate content codec will be created automatically depending on properties of the entity enclosed with the message.
    Direct channel I/O Content codes are optimized to read data directly from or write data directly to the underlying I/O session's channel, whenever possible avoiding intermediate buffering in a session buffer. Moreover, those codecs that do not perform any content transformation (Content-Length delimited and identity codecs, for example) can leverage NIO java.nio.FileChannel methods for significantly improved performance of file transfer operations both inbound and outbound. If the actual content decoder implements FileContentDecoder one can make use of its methods to read incoming content directly to a file bypassing an intermediate java.nio.ByteBuffer. //Prepare file channel FileChannel dst; //Make use of direct file I/O if possible if (decoder instanceof FileContentDecoder) { long Bytesread = ((FileContentDecoder) decoder) .transfer(dst, 0, 2048); // Decode will be marked as complete when // the content entity is fully transmitted if (decoder.isCompleted()) { // Done } } ]]> If the actual content encoder implements FileContentEncoder one can make use of its methods to write outgoing content directly from a file bypassing an intermediate java.nio.ByteBuffer. // Prepare file channel FileChannel src; // Make use of direct file I/O if possible if (encoder instanceof FileContentEncoder) { // Write data out long bytesWritten = ((FileContentEncoder) encoder) .transfer(src, 0, 2048); // Mark content entity as fully transferred when done encoder.complete(); } ]]>
    HTTP I/O event dispatchers HTTP I/O event dispatchers serve to convert generic I/O events triggered by an I/O reactor to HTTP protocol specific events. They rely on NHttpClientEventHandler and NHttpServerEventHandler interfaces to propagate HTTP protocol events to a HTTP protocol handler. Server side HTTP I/O events as defined by the NHttpServerEventHandler interface: <methodname>connected</methodname>: Triggered when a new incoming connection has been created. <methodname>requestReceived</methodname>: Triggered when a new HTTP request is received. The connection passed as a parameter to this method is guaranteed to return a valid HTTP request object. If the request received encloses a request entity this method will be followed a series of inputReady events to transfer the request content. <methodname>inputReady</methodname>: Triggered when the underlying channel is ready for reading a new portion of the request entity through the corresponding content decoder. If the content consumer is unable to process the incoming content, input event notifications can temporarily suspended using IOControl interface (super interface of NHttpServerConnection). Please note that the NHttpServerConnection and ContentDecoder objects are not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread to resume input event notifications when the handler is capable of processing more content. <methodname>responseReady</methodname>: Triggered when the connection is ready to accept new HTTP response. The protocol handler does not have to submit a response if it is not ready. <methodname>outputReady</methodname>: Triggered when the underlying channel is ready for writing a next portion of the response entity through the corresponding content encoder. If the content producer is unable to generate the outgoing content, output event notifications can be temporarily suspended using IOControl interface (super interface of NHttpServerConnection). Please note that the NHttpServerConnection and ContentEncoder objects are not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread to resume output event notifications when more content is made available. <methodname>exception</methodname>: Triggered when an I/O error occurrs while reading from or writing to the underlying channel or when an HTTP protocol violation occurs while receiving an HTTP request. <methodname>timeout</methodname>: Triggered when no input is detected on this connection over the maximum period of inactivity. <methodname>closed</methodname>: Triggered when the connection has been closed. Client side HTTP I/O events as defined by the NHttpClientEventHandler interface: <methodname>connected</methodname>: Triggered when a new outgoing connection has been created. The attachment object passed as a parameter to this event is an arbitrary object that was attached to the session request. <methodname>requestReady</methodname>: Triggered when the connection is ready to accept new HTTP request. The protocol handler does not have to submit a request if it is not ready. <methodname>outputReady</methodname>: Triggered when the underlying channel is ready for writing a next portion of the request entity through the corresponding content encoder. If the content producer is unable to generate the outgoing content, output event notifications can be temporarily suspended using IOControl interface (super interface of NHttpClientConnection). Please note that the NHttpClientConnection and ContentEncoder objects are not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread to resume output event notifications when more content is made available. <methodname>responseReceived</methodname>: Triggered when an HTTP response is received. The connection passed as a parameter to this method is guaranteed to return a valid HTTP response object. If the response received encloses a response entity this method will be followed a series of inputReady events to transfer the response content. <methodname>inputReady</methodname>: Triggered when the underlying channel is ready for reading a new portion of the response entity through the corresponding content decoder. If the content consumer is unable to process the incoming content, input event notifications can be temporarily suspended using IOControl interface (super interface of NHttpClientConnection). Please note that the NHttpClientConnection and ContentDecoder objects are not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread to resume input event notifications when the handler is capable of processing more content. <methodname>exception</methodname>: Triggered when an I/O error occurs while reading from or writing to the underlying channel or when an HTTP protocol violation occurs while receiving an HTTP response. <methodname>timeout</methodname>: Triggered when no input is detected on this connection over the maximum period of inactivity. <methodname>closed</methodname>: Triggered when the connection has been closed.
    Non-blocking HTTP content producers As discussed previously the process of content transfer for non-blocking connections works completely differently compared to that for blocking connections. For obvious reasons classic I/O abstraction based on inherently blocking java.io.InputStream and java.io.OutputStream classes is not well suited for asynchronous data transfer. In order to avoid inefficient and potentially blocking I/O operation redirection through java.nio.channels.Channles#newChannel non-blocking HTTP entities are expected to implement NIO specific extension interface HttpAsyncContentProducer. The HttpAsyncContentProducer interface defines several additional method for efficient streaming of content to a non-blocking HTTP connection: <methodname>produceContent</methodname>: Invoked to write out a chunk of content to the ContentEncoder . The IOControl interface can be used to suspend output events if the entity is temporarily unable to produce more content. When all content is finished, the producer MUST call ContentEncoder#complete(). Failure to do so may cause the entity to be incorrectly delimited. Please note that the ContentEncoder object is not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread resume output event notifications when more content is made available. <methodname>isRepeatable</methodname>: Determines whether or not this producer is capable of producing its content more than once. Repeatable content producers are expected to be able to recreate their content even after having been closed. <methodname>close</methodname>: Closes the producer and releases all resources currently allocated by it.
    Creating non-blocking entities Several HTTP entity implementations included in HttpCore NIO support HttpAsyncContentProducer interface: NByteArrayEntity NStringEntity NFileEntity
    <classname>NByteArrayEntity</classname> This is a simple self-contained repeatable entity, which receives its content from a given byte array. This byte array is supplied to the constructor.
    <classname>NStringEntity</classname> This is a simple, self-contained, repeatable entity that retrieves its data from a java.lang.String object. It has 2 constructors, one simply constructs with a given string where the other also takes a character encoding for the data in the java.lang.String.
    <classname>NFileEntity</classname> This entity reads its content body from a file. This class is mostly used to stream large files of different types, so one needs to supply the content type of the file to make sure the content can be correctly recognized and processed by the recipient. The NHttpEntity will make use of the direct channel I/O whenever possible, provided the content encoder is capable of transferring data directly from a file to the socket of the underlying connection.
    Non-blocking HTTP protocol handlers
    Asynchronous HTTP service HttpAsyncService is a fully asynchronous HTTP server side protocol handler based on the non-blocking (NIO) I/O model. HttpAsyncService translates individual events fired through the NHttpServerEventHandler interface into logically related HTTP message exchanges. Upon receiving an incoming request the HttpAsyncService verifies the message for compliance with the server expectations using HttpAsyncExpectationVerifier, if provided, and then HttpAsyncRequestHandlerResolver is used to resolve the request URI to a particular HttpAsyncRequestHandler intended to handle the request with the given URI. The protocol handler uses the selected HttpAsyncRequestHandler instance to process the incoming request and to generate an outgoing response. HttpAsyncService relies on 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 HTTP request handlers are expected to implement application specific content generation and processing.
    Non-blocking HTTP request handlers HttpAsyncRequestHandler represents a routine for asynchronous processing of a specific group of non-blocking 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. rh = new HttpAsyncRequestHandler() { public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) { // Buffer request content in memory for simplicity return new BasicAsyncRequestConsumer(); } public void handle( final HttpRequest request, final HttpAsyncExchange httpexchange, final HttpContext context) throws HttpException, IOException { HttpResponse response = httpexchange.getResponse(); response.setStatusCode(HttpStatus.SC_OK); NFileEntity body = new NFileEntity(new File("static.html"), ContentType.create("text/html", Consts.UTF_8)); response.setEntity(body); httpexchange.submitResponse(new BasicAsyncResponseProducer(response)); } }; ]]> Request handlers must be implemented in a thread-safe manner. Similarly to servlets, request handlers should not use instance variables unless access to those variables are synchronized.
    Asynchronous HTTP exchange The most fundamental difference of the non-blocking request handlers compared to their blocking counterparts is ability to defer transmission of the HTTP response back to the client without blocking the I/O thread by delegating the process of handling the HTTP request to a worker thread or another service. The instance of HttpAsyncExchange passed as a parameter to the HttpAsyncRequestHandler#handle method to submit a response as at a later point once response content becomes available. The HttpAsyncExchange interface can be interacted with using the following methods: <methodname>getRequest</methodname>: Returns the received HTTP request message. <methodname>getResponse</methodname>: Returns the default HTTP response message that can submitted once ready. <methodname>submitResponse</methodname>: Submits an HTTP response and completed the message exchange. <methodname>isCompleted</methodname>: Determines whether or not the message exchange has been completed. <methodname>setCallback</methodname>: Sets Cancellable callback to be invoked in case the underlying connection times out or gets terminated prematurely by the client. This callback can be used to cancel a long running response generating process if a response is no longer needed. <methodname>setTimeout</methodname>: Sets timeout for this message exchange. <methodname>getTimeout</methodname>: Returns timeout for this message exchange. rh = new HttpAsyncRequestHandler() { public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) { // Buffer request content in memory for simplicity return new BasicAsyncRequestConsumer(); } public void handle( final HttpRequest request, final HttpAsyncExchange httpexchange, final HttpContext context) throws HttpException, IOException { new Thread() { @Override public void run() { try { Thread.sleep(10); } catch(InterruptedException ie) {} HttpResponse response = httpexchange.getResponse(); response.setStatusCode(HttpStatus.SC_OK); NFileEntity body = new NFileEntity(new File("static.html"), ContentType.create("text/html", Consts.UTF_8)); response.setEntity(body); httpexchange.submitResponse(new BasicAsyncResponseProducer(response)); } }.start(); } }; ]]> Please note HttpResponse instances are not thread-safe and may not be modified concurrently. Non-blocking request handlers must ensure HTTP response cannot be accessed by more than one thread at a time.
    Asynchronous HTTP request consumer HttpAsyncRequestConsumer facilitates the process of asynchronous processing of HTTP requests. It is a callback interface used by HttpAsyncRequestHandlers to process an incoming HTTP request message and to stream its content from a non-blocking server side HTTP connection. HTTP I/O events and methods as defined by the HttpAsyncRequestConsumer interface: <methodname>requestReceived</methodname>: Invoked when a HTTP request message is received. <methodname>consumeContent</methodname>: Invoked to process a chunk of content from the ContentDecoder. The IOControl interface can be used to suspend input events if the consumer is temporarily unable to consume more content. The consumer can use the ContentDecoder#isCompleted() method to find out whether or not the message content has been fully consumed. Please note that the ContentDecoder object is not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread to resume input event notifications when the consumer is capable of processing more content. This event is invoked only if the incoming request message has a content entity enclosed in it. <methodname>requestCompleted</methodname>: Invoked to signal that the request has been fully processed. <methodname>failed</methodname>: Invoked to signal that the request processing terminated abnormally. <methodname>getException</methodname>: Returns an exception in case of an abnormal termination. This method returns null if the request execution is still ongoing or if it completed successfully. <methodname>getResult</methodname>: Returns a result of the request execution, when available. This method returns null if the request execution is still ongoing. <methodname>isDone</methodname>: Determines whether or not the request execution completed. If the request processing terminated normally getResult() can be used to obtain the result. If the request processing terminated abnormally getException() can be used to obtain the cause. <methodname>close</methodname>: Closes the consumer and releases all resources currently allocated by it. HttpAsyncRequestConsumer implementations are expected to be thread-safe. BasicAsyncRequestConsumer is a very basic implementation of the HttpAsyncRequestConsumer interface shipped with the library. Please note that this consumer buffers request content in memory and therefore should be used for relatively small request messages.
    Asynchronous HTTP response producer HttpAsyncResponseProducer facilitates the process of asynchronous generation of HTTP responses. It is a callback interface used by HttpAsyncRequestHandlers to generate an HTTP response message and to stream its content to a non-blocking server side HTTP connection. HTTP I/O events and methods as defined by the HttpAsyncResponseProducer interface: <methodname>generateResponse</methodname>: Invoked to generate a HTTP response message header. <methodname>produceContent</methodname>: Invoked to write out a chunk of content to the ContentEncoder. The IOControl interface can be used to suspend output events if the producer is temporarily unable to produce more content. When all content is finished, the producer MUST call ContentEncoder#complete(). Failure to do so may cause the entity to be incorrectly delimited. Please note that the ContentEncoder object is not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread resume output event notifications when more content is made available. This event is invoked only for if the outgoing response message has a content entity enclosed in it, that is HttpResponse#getEntity() returns null. <methodname>responseCompleted</methodname>: Invoked to signal that the response has been fully written out. <methodname>failed</methodname>: Invoked to signal that the response processing terminated abnormally. <methodname>close</methodname>: Closes the producer and releases all resources currently allocated by it. HttpAsyncResponseProducer implementations are expected to be thread-safe. BasicAsyncResponseProducer is a basic implementation of the HttpAsyncResponseProducer interface shipped with the library. The producer can make use of the HttpAsyncContentProducer interface to efficiently stream out message content to a non-blocking HTTP connection, if it is implemented by the HttpEntity enclosed in the response.
    Non-blocking request handler resolver The management of non-blocking HTTP request handlers is quite similar to that of blocking HTTP request handlers. Usually an instance of HttpAsyncRequestHandlerResolver is used to maintain a registry of request handlers and to matches a request URI to a particular request handler. HttpCore includes only a very simple implementation of the request handler resolver based on a trivial pattern matching algorithm: HttpAsyncRequestHandlerRegistry supports only three formats: *, <uri>* and *<uri>. myRequestHandler1 = <...> HttpAsyncRequestHandler myRequestHandler2 = <...> HttpAsyncRequestHandler myRequestHandler3 = <...> UriHttpAsyncRequestHandlerMapper handlerReqistry = new UriHttpAsyncRequestHandlerMapper(); handlerReqistry.register("/service/*", myRequestHandler1); handlerReqistry.register("*.do", myRequestHandler2); handlerReqistry.register("*", myRequestHandler3); ]]> Users are encouraged to provide more sophisticated implementations of HttpAsyncRequestHandlerResolver, for instance, based on regular expressions.
    Asynchronous HTTP request executor HttpAsyncRequestExecutor is a fully asynchronous client side HTTP protocol handler based on the NIO (non-blocking) I/O model. HttpAsyncRequestExecutor translates individual events fired through the NHttpClientEventHandler interface into logically related HTTP message exchanges. HttpAsyncRequestExecutor relies on HttpAsyncRequestExecutionHandler to implement application specific content generation and processing and to handle logically related series of HTTP request / response exchanges, which may also span across multiple connections. HttpProcessor provided by the HttpAsyncRequestExecutionHandler instance will be used to generate mandatory protocol headers for all outgoing messages and apply common, cross-cutting message transformations to all incoming and outgoing messages. The caller is expected to pass an instance of HttpAsyncRequestExecutionHandler to be used for the next series of HTTP message exchanges through the connection context using HttpAsyncRequestExecutor#HTTP_HANDLER attribute. HTTP exchange sequence is considered complete when the HttpAsyncRequestExecutionHandler#isDone() method returns true. The HttpAsyncRequester utility class can be used to abstract away low level details of HttpAsyncRequestExecutionHandler management. Please note HttpAsyncRequester supports single HTTP request / response exchanges only. It does not support HTTP authentication and does not handle redirects automatically. Future future = requester.execute( new BasicAsyncRequestProducer( new HttpHost("localhost"), new BasicHttpRequest("GET", "/")), new BasicAsyncResponseConsumer(), conn); HttpResponse response = future.get(); ]]>
    Asynchronous HTTP request producer HttpAsyncRequestProducer facilitates the process of asynchronous generation of HTTP requests. It is a callback interface whose methods get invoked to generate an HTTP request message and to stream message content to a non-blocking client side HTTP connection. Repeatable request producers capable of generating the same request message more than once can be reset to their initial state by calling the resetRequest() method, at which point request producers are expected to release currently allocated resources that are no longer needed or re-acquire resources needed to repeat the process. HTTP I/O events and methods as defined by the HttpAsyncRequestProducer interface: <methodname>getTarget</methodname>: Invoked to obtain the request target host. <methodname>generateRequest</methodname>: Invoked to generate a HTTP request message header. The message is expected to implement the HttpEntityEnclosingRequest interface if it is to enclose a content entity. <methodname>produceContent</methodname>: Invoked to write out a chunk of content to the ContentEncoder. The IOControl interface can be used to suspend output events if the producer is temporarily unable to produce more content. When all content is finished, the producer MUST call ContentEncoder#complete(). Failure to do so may cause the entity to be incorrectly delimited Please note that the ContentEncoder object is not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread resume output event notifications when more content is made available. This event is invoked only for if the outgoing request message has a content entity enclosed in it, that is HttpEntityEnclosingRequest#getEntity() returns null . <methodname>requestCompleted</methodname>: Invoked to signal that the request has been fully written out. <methodname>failed</methodname>: Invoked to signal that the request processing terminated abnormally. <methodname>resetRequest</methodname>: Invoked to reset the producer to its initial state. Repeatable request producers are expected to release currently allocated resources that are no longer needed or re-acquire resources needed to repeat the process. <methodname>close</methodname>: Closes the producer and releases all resources currently allocated by it. HttpAsyncRequestProducer implementations are expected to be thread-safe. BasicAsyncRequestProducer is a basic implementation of the HttpAsyncRequestProducer interface shipped with the library. The producer can make use of the HttpAsyncContentProducer interface to efficiently stream out message content to a non-blocking HTTP connection, if it is implemented by the HttpEntity enclosed in the request.
    Asynchronous HTTP response consumer HttpAsyncResponseConsumer facilitates the process of asynchronous processing of HTTP responses. It is a callback interface whose methods get invoked to process an HTTP response message and to stream message content from a non-blocking client side HTTP connection. HTTP I/O events and methods as defined by the HttpAsyncResponseConsumer interface: <methodname>responseReceived</methodname>: Invoked when a HTTP response message is received. <methodname>consumeContent</methodname>: Invoked to process a chunk of content from the ContentDecoder. The IOControl interface can be used to suspend input events if the consumer is temporarily unable to consume more content. The consumer can use the ContentDecoder#isCompleted() method to find out whether or not the message content has been fully consumed. Please note that the ContentDecoder object is not thread-safe and should only be used within the context of this method call. The IOControl object can be shared and used on other thread to resume input event notifications when the consumer is capable of processing more content. This event is invoked only for if the incoming response message has a content entity enclosed in it. <methodname>responseCompleted</methodname>: Invoked to signal that the response has been fully processed. <methodname>failed</methodname>: Invoked to signal that the response processing terminated abnormally. <methodname>getException</methodname>: Returns an exception in case of an abnormal termination. This method returns null if the response processing is still ongoing or if it completed successfully. <methodname>getResult</methodname>: Returns a result of the response processing, when available. This method returns null if the response processing is still ongoing. <methodname>isDone</methodname>: Determines whether or not the response processing completed. If the response processing terminated normally getResult() can be used to obtain the result. If the response processing terminated abnormally getException() can be used to obtain the cause. <methodname>close</methodname>: Closes the consumer and releases all resources currently allocated by it. HttpAsyncResponseConsumer implementations are expected to be thread-safe. BasicAsyncResponseConsumer is a very basic implementation of the HttpAsyncResponseConsumer interface shipped with the library. Please note that this consumer buffers response content in memory and therefore should be used for relatively small response messages.
    Non-blocking connection pools Non-blocking connection pools are quite similar to blocking one with one significant distinction that they have to reply an I/O reactor to establish new connections. As a result connections leased from a non-blocking pool are returned fully initialized and already bound to a particular I/O session. Non-blocking connections managed by a connection pool cannot be bound to an arbitrary I/O session. BasicNIOConnPool connpool = new BasicNIOConnPool(ioreactor); connpool.lease(target, null, 10, TimeUnit.SECONDS, new FutureCallback() { @Override public void completed(BasicNIOPoolEntry entry) { NHttpClientConnection conn = entry.getConnection(); System.out.println("Connection successfully leased"); // Update connection context and request output conn.requestOutput(); } @Override public void failed(Exception ex) { System.out.println("Connection request failed"); ex.printStackTrace(); } @Override public void cancelled() { } }); ]]> Please note due to event-driven nature of asynchronous communication model it is quite difficult to ensure proper release of persistent connections back to the pool. One can make use of HttpAsyncRequester to handle connection lease and release behind the scene. HttpProcessor httpproc = <...> BasicNIOConnPool connpool = new BasicNIOConnPool(ioreactor); HttpAsyncRequester requester = new HttpAsyncRequester(httpproc); HttpHost target = new HttpHost("localhost"); Future future = requester.execute( new BasicAsyncRequestProducer( new HttpHost("localhost"), new BasicHttpRequest("GET", "/")), new BasicAsyncResponseConsumer(), connpool); ]]>
    Non-blocking TLS/SSL
    SSL I/O session SSLIOSession is a decorator class intended to transparently extend any arbitrary IOSession with transport layer security capabilities based on the SSL/TLS protocol. Default HTTP connection implementations and protocol handlers should be able to work with SSL sessions without special preconditions or modifications. SSLIOSession sslsession = new SSLIOSession( iosession, SSLMode.CLIENT, sslcontext, null); iosession.setAttribute(SSLIOSession.SESSION_KEY, sslsession); NHttpClientConnection conn = new DefaultNHttpClientConnection( sslsession, 8 * 1024); ]]> One can also use SSLNHttpClientConnectionFactory or SSLNHttpServerConnectionFactory classes to conveniently create SSL encrypterd HTTP connections. SSLNHttpClientConnectionFactory connfactory = new SSLNHttpClientConnectionFactory( sslcontext, null, ConnectionConfig.DEFAULT); NHttpClientConnection conn = connfactory.createConnection(iosession); ]]>
    SSL setup handler Applications can customize various aspects of the TLS/SSl protocol by passing a custom implementation of the SSLSetupHandler interface. SSL events as defined by the SSLSetupHandler interface: <methodname>initalize</methodname>: Triggered when the SSL connection is being initialized. The handler can use this callback to customize properties of the javax.net.ssl.SSLEngine used to establish the SSL session. <methodname>verify</methodname>: Triggered when the SSL connection has been established and initial SSL handshake has been successfully completed. The handler can use this callback to verify properties of the SSLSession. For instance this would be the right place to enforce SSL cipher strength, validate certificate chain and do hostname checks. SSLIOSession sslsession = new SSLIOSession( iosession, SSLMode.CLIENT, sslcontext, new SSLSetupHandler() { public void initalize(final SSLEngine sslengine) throws SSLException { // Enforce strong ciphers sslengine.setEnabledCipherSuites(new String[] { "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" }); } public void verify( final IOSession iosession, final SSLSession sslsession) throws SSLException { X509Certificate[] certs = sslsession.getPeerCertificateChain(); // Examine peer certificate chain for (X509Certificate cert: certs) { System.out.println(cert.toString()); } } }); ]]> SSLSetupHandler impelemntations can also be used with the SSLNHttpClientConnectionFactory or SSLNHttpServerConnectionFactory classes. SSLSetupHandler mysslhandler = new SSLSetupHandler() { public void initalize(final SSLEngine sslengine) throws SSLException { // Enforce strong ciphers sslengine.setEnabledCipherSuites(new String[] { "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" }); } public void verify( final IOSession iosession, final SSLSession sslsession) throws SSLException { } }; SSLNHttpClientConnectionFactory connfactory = new SSLNHttpClientConnectionFactory( sslcontext, mysslhandler, ConnectionConfig.DEFAULT); NHttpClientConnection conn = connfactory.createConnection(iosession); ]]>
    TLS/SSL aware I/O event dispatches Default IOEventDispatch implementations shipped with the library such as DefaultHttpServerIODispatch and DefaultHttpClientIODispatch automatically detect SSL encrypted sessions and handle SSL transport aspects transparently. However, custom I/O event dispatchers that do not extend AbstractIODispatch are required to take some additional actions to ensure correct functioning of the transport layer encryption. The I/O dispatch may need to call SSLIOSession#initalize() method in order to put the SSL session either into a client or a server mode, if the SSL session has not been yet initialized. When the underlying I/O session is input ready, the I/O dispatcher should check whether the SSL I/O session is ready to produce input data by calling SSLIOSession#isAppInputReady(), pass control to the protocol handler if it is, and finally call SSLIOSession#inboundTransport() method in order to do the necessary SSL handshaking and decrypt input data. When the underlying I/O session is output ready, the I/O dispatcher should check whether the SSL I/O session is ready to accept output data by calling SSLIOSession#isAppOutputReady(), pass control to the protocol handler if it is, and finally call SSLIOSession#outboundTransport() method in order to do the necessary SSL handshaking and encrypt application data.
    httpcomponents-core-4.3.2/src/docbkx/advanced.xml0100644 0000000 0000000 00000040770 12276755417 020642 0ustar000000000 0000000 Advanced topics
    HTTP message parsing and formatting framework HTTP message processing framework is designed to be expressive and flexible while remaining memory efficient and fast. HttpCore HTTP message processing code achieves near zero intermediate garbage and near zero-copy buffering for its parsing and formatting operations. The same HTTP message parsing and formatting API and implementations are used by both the blocking and non-blocking transport implementations, which helps ensure a consistent behavior of HTTP services regardless of the I/O model.
    HTTP line parsing and formatting HttpCore utilizes a number of low level components for all its line parsing and formatting methods. CharArrayBuffer represents a sequence of characters, usually a single line in an HTTP message stream such as a request line, a status line or a header. Internally CharArrayBuffer is backed by an array of chars, which can be expanded to accommodate more input if needed. CharArrayBuffer also provides a number of utility methods for manipulating content of the buffer, storing more data and retrieving subsets of data. stdout > ParserCursor represents a context of a parsing operation: the bounds limiting the scope of the parsing operation and the current position the parsing operation is expected to start at. stdout > 7>14] ]]> LineParser is the 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 I/O mechanism. stdout > stdout > LineFormatter for formatting elements of the head section of an HTTP message. This is the complement to LineParser . There are individual methods for formatting a request line, a status line, or a header line. Please note the formatting does not include the trailing line break sequence CR-LF. stdout > HeaderValueParser is the interface for parsing header values into elements. stdout > HeaderValueFormatter is the interface for formatting elements of a header value. This is the complement to HeaderValueParser . stdout >
    HTTP message streams and session I/O buffers HttpCore provides a number of utility classes for the blocking and non-blocking I/O models that facilitate the processing of HTTP message streams, simplify handling of CR-LF delimited lines in HTTP messages and manage intermediate data buffering. HTTP connection implementations usually rely on session input/output buffers for reading and writing data from and to an HTTP message stream. Session input/output buffer implementations are I/O model specific and are optimized either for blocking or non-blocking operations. Blocking HTTP connections use socket bound session buffers to transfer data. Session buffer interfaces are similar to java.io.InputStream / java.io.OutputStream classes, but they also provide methods for reading and writing CR-LF delimited lines. Socket socket2 = <...> HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); SessionInputBufferImpl inbuffer = new SessionInputBufferImpl(metrics, 8 * 1024); inbuffer.bind(socket1.getInputStream()); SessionOutputBufferImpl outbuffer = new SessionOutputBufferImpl(metrics, 8 * 1024); outbuffer.bind(socket2.getOutputStream()); CharArrayBuffer linebuf = new CharArrayBuffer(1024); inbuffer.readLine(linebuf); outbuffer.writeLine(linebuf); ]]> Non-blocking HTTP connections use session buffers optimized for reading and writing data from and to non-blocking NIO channels. NIO session input/output sessions help deal with CR-LF delimited lines in a non-blocking I/O mode. WritableByteChannel channel2 = <...> SessionInputBuffer inbuffer = new SessionInputBufferImpl(8 * 1024); SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(8 * 1024); CharArrayBuffer linebuf = new CharArrayBuffer(1024); boolean endOfStream = false; int bytesRead = inbuffer.fill(channel1); if (bytesRead == -1) { endOfStream = true; } if (inbuffer.readLine(linebuf, endOfStream)) { outbuffer.writeLine(linebuf); } if (outbuffer.hasData()) { outbuffer.flush(channel2); } ]]>
    HTTP message parsers and formatters HttpCore also provides coarse-grained facade type interfaces for parsing and formatting of HTTP messages. Default implementations of those interfaces build upon the functionality provided by SessionInputBuffer / SessionOutputBuffer and HttpLineParser / HttpLineFormatter implementations. Example of HTTP request parsing / writing for blocking HTTP connections: SessionOutputBuffer outbuffer = <...> HttpMessageParser requestParser = new DefaultHttpRequestParser( inbuffer); HttpRequest request = requestParser.parse(); HttpMessageWriter requestWriter = new DefaultHttpRequestWriter( outbuffer); requestWriter.write(request); ]]> Example of HTTP response parsing / writing for blocking HTTP connections: SessionOutputBuffer outbuffer = <...> HttpMessageParser responseParser = new DefaultHttpResponseParser( inbuffer); HttpResponse response = responseParser.parse(); HttpMessageWriter responseWriter = new DefaultHttpResponseWriter( outbuffer); responseWriter.write(response); ]]> Custom message parsers and writers can be plugged into the message processing pipeline through a custom connection factory: responseWriterFactory = new HttpMessageWriterFactory() { @Override public HttpMessageWriter create( SessionOutputBuffer buffer) { HttpMessageWriter customWriter = <...> return customWriter; } }; HttpMessageParserFactory requestParserFactory = new HttpMessageParserFactory() { @Override public HttpMessageParser create( SessionInputBuffer buffer, MessageConstraints constraints) { HttpMessageParser customParser = <...> return customParser; } }; HttpConnectionFactory cf = new DefaultBHttpServerConnectionFactory( ConnectionConfig.DEFAULT, requestParserFactory, responseWriterFactory); Socket socket = <...> DefaultBHttpServerConnection conn = cf.createConnection(socket); ]]> Example of HTTP request parsing / writing for non-blocking HTTP connections: SessionOutputBuffer outbuffer = <...> NHttpMessageParser requestParser = new DefaultHttpRequestParser( inbuffer); HttpRequest request = requestParser.parse(); NHttpMessageWriter requestWriter = new DefaultHttpRequestWriter( outbuffer); requestWriter.write(request); ]]> Example of HTTP response parsing / writing for non-blocking HTTP connections: SessionOutputBuffer outbuffer = <...> NHttpMessageParser responseParser = new DefaultHttpResponseParser( inbuffer); HttpResponse response = responseParser.parse(); NHttpMessageWriter responseWriter = new DefaultHttpResponseWriter( outbuffer); responseWriter.write(response); ]]>
    Custom non-blocking message parsers and writers can be plugged into the message processing pipeline through a custom connection factory: responseWriterFactory = new NHttpMessageWriterFactory() { @Override public NHttpMessageWriter create(SessionOutputBuffer buffer) { NHttpMessageWriter customWriter = <...> return customWriter; } }; NHttpMessageParserFactory requestParserFactory = new NHttpMessageParserFactory() { @Override public NHttpMessageParser create( SessionInputBuffer buffer, MessageConstraints constraints) { NHttpMessageParser customParser = <...> return customParser; } }; NHttpConnectionFactory cf = new DefaultNHttpServerConnectionFactory( null, requestParserFactory, responseWriterFactory, ConnectionConfig.DEFAULT); IOSession iosession = <...> DefaultNHttpServerConnection conn = cf.createConnection(iosession); ]]>
    HTTP header parsing on demand The default implementations of HttpMessageParser and NHttpMessageParser interfaces do not parse HTTP headers immediately. Parsing of header value is deferred until its properties are accessed. Those headers that are never used by the application will not be parsed at all. The CharArrayBuffer backing the header can be obtained through an optional FormattedHeader interface. Header h1 = response.getFirstHeader("Content-Type"); if (h1 instanceof FormattedHeader) { CharArrayBuffer buf = ((FormattedHeader) h1).getBuffer(); System.out.println(buf); } ]]>
    httpcomponents-core-4.3.2/src/docbkx/preface.xml0100644 0000000 0000000 00000006521 12276755417 020476 0ustar000000000 0000000 Preface HttpCore is a set of components implementing the most fundamental aspects of the HTTP protocol that are nonetheless sufficient to develop full-featured client-side and server-side HTTP services with a minimal footprint. HttpCore has the following scope and goals:
    HttpCore Scope A consistent API for building client / proxy / server side HTTP services A consistent API for building both synchronous and asynchronous HTTP services A set of low level components based on blocking (classic) and non-blocking (NIO) I/O models
    HttpCore Goals Implementation of the most fundamental HTTP transport aspects Balance between good performance and the clarity & expressiveness of API Small (predictable) memory footprint Self-contained library (no external dependencies beyond JRE)
    What HttpCore is NOT A replacement for HttpClient A replacement for Servlet APIs
    httpcomponents-core-4.3.2/src/docbkx/index.xml0100644 0000000 0000000 00000005626 12276755417 020205 0ustar000000000 0000000 HttpCore Tutorial &version; Oleg Kalnichevski Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. httpcomponents-core-4.3.2/src/docbkx/fundamentals.xml0100644 0000000 0000000 00000156350 12276755417 021560 0ustar000000000 0000000 HTTP message fundamentals and classic synchronous I/O
    HTTP messages
    Structure A HTTP message consists of a header and an optional body. The message header of an HTTP request consists of a request line and a collection of header fields. The message header of an HTTP response consists of a status line and a collection of header fields. All HTTP messages must include the protocol version. Some HTTP messages can optionally enclose a content body. HttpCore defines the HTTP message object model to follow this definition closely, and provides extensive support for serialization (formatting) and deserialization (parsing) of HTTP message elements.
    Basic operations
    HTTP request message HTTP request is a message sent from the client to the server. The first line of that message includes the method to apply to the resource, the identifier of the resource, and the protocol version in use. stdout >
    HTTP response message HTTP response is a message sent by the server back to the client after having received and interpreted a request message. The first line of that message consists of the protocol version followed by a numeric status code and its associated textual phrase. stdout >
    HTTP message common properties and methods An HTTP message can contain a number of headers describing properties of the message such as the content length, content type, and so on. HttpCore provides methods to retrieve, add, remove, and enumerate such headers. stdout > There is an efficient way to obtain all headers of a given type using the HeaderIterator interface. stdout > It also provides convenience methods to parse HTTP messages into individual header elements. stdout > HTTP headers are tokenized into individual header elements only on demand. HTTP headers received over an HTTP connection are stored internally as an array of characters and parsed lazily only when you access their properties.
    HTTP entity HTTP messages can carry a content entity associated with the request or response. Entities can be found in some requests and in some responses, as they are optional. Requests that use entities are referred to as entity-enclosing requests. The HTTP specification defines two entity-enclosing methods: POST and PUT. Responses are usually expected to enclose a content entity. There are exceptions to this rule such as responses to HEAD method and 204 No Content, 304 Not Modified, 205 Reset Content responses. HttpCore distinguishes three kinds of entities, depending on where their 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 connection. Streamed entities are generally not 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 repeatable. wrapping: The content is obtained from another entity. This distinction is important for connection management with incoming entities. For an application that creates entities and only sends them using the HttpCore framework, the difference between streamed and self-contained is of little importance. In that case, we suggest you consider non-repeatable entities as streamed, and those that are repeatable as self-contained.
    Repeatable entities An entity can be repeatable, meaning you can read its content more than once. This is only possible with self-contained entities (like ByteArrayEntity or StringEntity).
    Using HTTP entities Since an entity can represent both binary and character content, it has support for character encodings (to support the latter, i.e. character content). The entity is created when executing a request with enclosed content or when the request was successful and the response body is used to send the result back to the client. To read the content from the entity, one can either retrieve the input stream via the HttpEntity#getContent() method, which returns an java.io.InputStream, or one can supply an output stream to the HttpEntity#writeTo(OutputStream) method, which will return once all content has been written to the given stream. The EntityUtils class exposes several static methods to simplify extracting the content or information from an entity. Instead of reading the java.io.InputStream directly, one can retrieve the complete content body in a string or byte array by using the methods from this class. When the entity has been received with an incoming message, the methods HttpEntity#getContentType() and HttpEntity#getContentLength() methods can be used for reading the common metadata such as Content-Type and Content-Length headers (if they are available). Since the Content-Type header can contain a character encoding for text mime-types like text/plain or text/html, the HttpEntity#getContentEncoding() method is used to read this information. If the headers aren't available, a length of -1 will be returned, and NULL for the content type. If the Content-Type header is available, a Header object will be returned. When creating an entity for a outgoing message, this meta data has to be supplied by the creator of the entity. stdout >
    Ensuring release of system resources In order to ensure proper release of system resources one must close the content stream associated with the entity. Please note that HttpEntity#writeTo(OutputStream) method is also required to ensure proper release of system resources once the entity has been fully written out. If this method obtains an instance of java.io.InputStream by calling HttpEntity#getContent(), it is also expected to close the stream in a finally clause. When working with streaming entities, one can use the EntityUtils#consume(HttpEntity) method to ensure that the entity content has been fully consumed and the underlying stream has been closed.
    Creating entities There are a few ways to create entities. HttpCore provides the following implementations: BasicHttpEntity ByteArrayEntity StringEntity InputStreamEntity FileEntity EntityTemplate HttpEntityWrapper BufferedHttpEntity
    <classname>BasicHttpEntity</classname> Exactly as the name implies, this basic entity represents an underlying stream. In general, use this class for entities received from HTTP messages. This entity has an empty constructor. After construction, it represents no content, and has a negative content length. One needs to set the content stream, and optionally the length. This can be done with the BasicHttpEntity#setContent(InputStream) and BasicHttpEntity#setContentLength(long) methods respectively.
    <classname>ByteArrayEntity</classname> ByteArrayEntity is a self-contained, repeatable entity that obtains its content from a given byte array. Supply the byte array to the constructor.
    <classname>StringEntity</classname> StringEntity is a self-contained, repeatable entity that obtains its content from a java.lang.String object. It has three constructors, one simply constructs with a given java.lang.String object; the second also takes a character encoding for the data in the string; the third allows the mime type to be specified. env = System.getenv(); for (Map.Entry envEntry : env.entrySet()) { sb.append(envEntry.getKey()) .append(": ").append(envEntry.getValue()) .append("\r\n"); } // construct without a character encoding (defaults to ISO-8859-1) HttpEntity myEntity1 = new StringEntity(sb.toString()); // alternatively construct with an encoding (mime type defaults to "text/plain") HttpEntity myEntity2 = new StringEntity(sb.toString(), Consts.UTF_8); // alternatively construct with an encoding and a mime type HttpEntity myEntity3 = new StringEntity(sb.toString(), ContentType.create("text/plain", Consts.UTF_8)); ]]>
    <classname>InputStreamEntity</classname> InputStreamEntity is a streamed, non-repeatable entity that obtains its content from an input stream. Construct it by supplying the input stream and the content length. Use the content length to limit the amount of data read from the java.io.InputStream. If the length matches the content length available on the input stream, then all data will be sent. Alternatively, a negative content length will read all data from the input stream, which is the same as supplying the exact content length, so use the length to limit the amount of data to read.
    <classname>FileEntity</classname> FileEntity is a self-contained, repeatable entity that obtains its content from a file. Use this mostly to stream large files of different types, where you need to supply the content type of the file, for instance, sending a zip file would require the content type application/zip, for XML application/xml.
    <classname>HttpEntityWrapper</classname> This is the base class for creating wrapped entities. The wrapping entity holds a reference to a wrapped entity 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.
    <classname>BufferedHttpEntity</classname> BufferedHttpEntity is a subclass of HttpEntityWrapper. Construct it by supplying another entity. It reads the content from the supplied entity, and buffers it in memory. This makes it possible to make a repeatable entity, from a non-repeatable entity. If the supplied entity is already repeatable, it simply passes calls through to the underlying entity.
    Blocking HTTP connections HTTP connections are responsible for HTTP message serialization and deserialization. One should rarely need to use HTTP connection objects directly. There are higher level protocol components intended for execution and processing of HTTP requests. However, in some cases direct interaction with HTTP connections may be necessary, for instance, to access properties such as the connection status, the socket timeout or the local and remote addresses. It is important to bear in mind that HTTP connections are not thread-safe. We strongly recommend limiting all interactions with HTTP connection objects to one thread. The only method of HttpConnection interface and its sub-interfaces which is safe to invoke from another thread is HttpConnection#shutdown() .
    Working with blocking HTTP connections HttpCore does not provide full support for opening connections because the process of establishing a new connection - especially on the client side - can be very complex when it involves one or more authenticating or/and tunneling proxies. Instead, blocking HTTP connections can be bound to any arbitrary network socket. DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); conn.bind(socket); System.out.println(conn.isOpen()); HttpConnectionMetrics metrics = conn.getMetrics(); System.out.println(metrics.getRequestCount()); System.out.println(metrics.getResponseCount()); System.out.println(metrics.getReceivedBytesCount()); System.out.println(metrics.getSentBytesCount()); ]]> HTTP connection interfaces, both client and server, send and receive messages in two stages. The message head is transmitted first. Depending on properties of the message head, a message body may follow it. Please note it is very important to always close the underlying content stream in order to signal that the processing of the message is complete. HTTP entities that stream out their content directly from the input stream of the underlying connection must ensure they fully consume the content of the message body for that connection to be potentially re-usable. Over-simplified process of request execution on the client side may look like this: DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); conn.bind(socket); HttpRequest request = new BasicHttpRequest("GET", "/"); conn.sendRequestHeader(request); HttpResponse response = conn.receiveResponseHeader(); conn.receiveResponseEntity(response); HttpEntity entity = response.getEntity(); if (entity != null) { // Do something useful with the entity and, when done, ensure all // content has been consumed, so that the underlying connection // can be re-used EntityUtils.consume(entity); } ]]> Over-simplified process of request handling on the server side may look like this: DefaultBHttpServerConnection conn = new DefaultBHttpServerConnection(8 * 1024); conn.bind(socket); HttpRequest request = conn.receiveRequestHeader(); if (request instanceof HttpEntityEnclosingRequest) { conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); HttpEntity entity = ((HttpEntityEnclosingRequest) request) .getEntity(); if (entity != null) { // Do something useful with the entity and, when done, ensure all // content has been consumed, so that the underlying connection // could be re-used EntityUtils.consume(entity); } } HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK") ; response.setEntity(new StringEntity("Got it") ); conn.sendResponseHeader(response); conn.sendResponseEntity(response); ]]> Please note that one should rarely need to transmit messages using these low level methods and should normally use the appropriate higher level HTTP service implementations instead.
    Content transfer with blocking I/O HTTP connections manage the process of the content transfer using the HttpEntity interface. HTTP connections generate an entity object that encapsulates the content stream of the incoming message. Please note that HttpServerConnection#receiveRequestEntity() and HttpClientConnection#receiveResponseEntity() do not retrieve or buffer any incoming data. They merely inject an appropriate content codec based on the properties of the incoming message. The content can be retrieved by reading from the content input stream of the enclosed entity using HttpEntity#getContent(). The incoming data will be decoded automatically and completely transparently to the data consumer. Likewise, HTTP connections rely on HttpEntity#writeTo(OutputStream) method to generate the content of an outgoing message. If an outgoing message encloses an entity, the content will be encoded automatically based on the properties of the message.
    Supported content transfer mechanisms Default implementations of HTTP connections support three content transfer mechanisms defined by the HTTP/1.1 specification: <literal>Content-Length</literal> delimited: The end of the content entity is determined by the value of the Content-Length header. Maximum entity length: Long#MAX_VALUE. Identity coding: The end of the content entity is demarcated by closing the underlying connection (end of stream condition). For obvious reasons the identity encoding can only be used on the server side. Maximum entity length: unlimited. Chunk coding: The content is sent in small chunks. Maximum entity length: unlimited. The appropriate content stream class will be created automatically depending on properties of the entity enclosed with the message.
    Terminating HTTP connections HTTP connections can be terminated either gracefully by calling HttpConnection#close() or forcibly by calling HttpConnection#shutdown(). The former tries to flush all buffered data prior to terminating the connection and may block indefinitely. The HttpConnection#close() method is not thread-safe. The latter terminates the connection without flushing internal buffers and returns control to the caller as soon as possible without blocking for long. The HttpConnection#shutdown() method is thread-safe.
    HTTP exception handling All HttpCore components potentially throw two types of exceptions: IOException in case of an I/O failure such as socket timeout or an socket reset and HttpException that signals an HTTP failure such as a violation of the HTTP protocol. Usually I/O errors are considered non-fatal and recoverable, whereas HTTP protocol errors are considered fatal and cannot be automatically recovered from.
    Protocol exception ProtocolException signals a fatal HTTP protocol violation that usually results in an immediate termination of the HTTP message processing.
    HTTP protocol processors 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; transparent content compression / decompression being a good example. Usually this is accomplished by using the 'Decorator' pattern where a wrapper entity class is used to decorate the original entity. Several protocol interceptors can be combined to form one logical unit. 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 the particular aspect of the HTTP protocol it 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.
    Standard protocol interceptors HttpCore comes with a number of most essential protocol interceptors for client and server HTTP processing.
    <classname>RequestContent</classname> RequestContent is the most important interceptor for outgoing requests. It is responsible for delimiting content length by adding the Content-Length or 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.
    <classname>ResponseContent</classname> ResponseContent is the most important interceptor for outgoing responses. It is responsible for delimiting content length by adding Content-Length or 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.
    <classname>RequestConnControl</classname> RequestConnControl is responsible for adding the Connection header to the outgoing requests, which is essential for managing persistence of HTTP/1.0 connections. This interceptor is recommended for client side protocol processors.
    <classname>ResponseConnControl</classname> ResponseConnControl is responsible for adding the Connection header to the outgoing responses, which is essential for managing persistence of HTTP/1.0 connections. This interceptor is recommended for server side protocol processors.
    <classname>RequestDate</classname> RequestDate is responsible for adding the Date header to the outgoing requests. This interceptor is optional for client side protocol processors.
    <classname>ResponseDate</classname> ResponseDate is responsible for adding the Date header to the outgoing responses. This interceptor is recommended for server side protocol processors.
    <classname>RequestExpectContinue</classname> RequestExpectContinue is responsible for enabling the 'expect-continue' handshake by adding the Expect header. This interceptor is recommended for client side protocol processors.
    <classname>RequestTargetHost</classname> RequestTargetHost is responsible for adding the Host header. This interceptor is required for client side protocol processors.
    <classname>RequestUserAgent</classname> RequestUserAgent is responsible for adding the User-Agent header. This interceptor is recommended for client side protocol processors.
    <classname>ResponseServer</classname> ResponseServer is responsible for adding the Server header. This interceptor is recommended for server side protocol processors.
    Working with protocol processors Usually HTTP protocol processors are used to pre-process incoming messages prior to executing application specific processing logic and to post-process outgoing messages. Send the request to the target host and get a response. httpproc.process(response, context); ]]> Please note the BasicHttpProcessor class does not synchronize access to its internal structures and therefore may not be thread-safe.
    HTTP context Protocol interceptors can collaborate by sharing information - such as a processing state - through an HTTP execution context. HTTP context is a structure that can be used to map an attribute name to an attribute value. Internally HTTP context implementations are usually backed by a HashMap. 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.
    Blocking HTTP protocol handlers
    HTTP service HttpService is a server side HTTP protocol handler based on the blocking I/O model that implements the essential requirements of the HTTP protocol for the server side message processing as described by RFC 2616. HttpService relies on HttpProcessor instance to generate mandatory protocol headers for all outgoing messages and apply common, cross-cutting message transformations to all incoming and outgoing messages, whereas HTTP request handlers are expected to take care of application specific content generation and processing.
    HTTP request handlers The HttpRequestHandler interface represents a routine for processing of a specific group of HTTP requests. HttpService is 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.
    Request handler resolver HTTP request handlers are usually managed by a HttpRequestHandlerResolver that matches a request URI to a request handler. HttpCore includes a very simple implementation of the request handler resolver based on a trivial pattern matching algorithm: HttpRequestHandlerRegistry supports only three formats: *, <uri>* and *<uri>. HttpRequestHandler myRequestHandler1 = <...> HttpRequestHandler myRequestHandler2 = <...> HttpRequestHandler myRequestHandler3 = <...> UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper(); handlerMapper.register("/service/*", myRequestHandler1); handlerMapper.register("*.do", myRequestHandler2); handlerMapper.register("*", myRequestHandler3); HttpService httpService = new HttpService(httpproc, handlerMapper); ]]> Users are encouraged to provide more sophisticated implementations of HttpRequestHandlerResolver - for instance, based on regular expressions.
    Using HTTP service to handle requests When fully initialized and configured, the HttpService can be used to execute and handle requests for active HTTP connections. The HttpService#handleRequest() method reads an incoming request, generates a response and sends it back to the client. This method can be executed in a loop to handle multiple requests on a persistent connection. The HttpService#handleRequest() method is safe to execute from multiple threads. This allows processing of requests on several connections simultaneously, as long as all the protocol interceptors and requests handlers used by the HttpService are thread-safe. HttpServerConnection conn = <...> HttpContext context = <...> boolean active = true; try { while (active && conn.isOpen()) { httpService.handleRequest(conn, context); } } finally { conn.shutdown(); } ]]>
    HTTP request executor HttpRequestExecutor is a client side HTTP protocol handler based on the blocking I/O model that implements the essential requirements of the HTTP protocol for the client side message processing, as described by RFC 2616. The HttpRequestExecutor relies on the HttpProcessor instance 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 HttpRequestExecutor once the request has been executed and a response has been received. HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new RequestContent()) .add(new RequestTargetHost()) .add(new RequestConnControl()) .add(new RequestUserAgent("MyClient/1.1")) .add(new RequestExpectContinue(true)) .build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpRequest request = new BasicHttpRequest("GET", "/"); HttpCoreContext context = HttpCoreContext.create(); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); httpexecutor.postProcess(response, httpproc, context); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); ]]> Methods of HttpRequestExecutor are safe to execute from multiple threads. This allows execution of requests on several connections simultaneously, as long as all the protocol interceptors used by the HttpRequestExecutor are thread-safe.
    Connection persistence / re-use The ConnectionReuseStrategy interface is intended to determine whether the underlying connection can be re-used for processing of further messages after the transmission of the current message has been completed. The default connection re-use strategy attempts to keep connections alive whenever possible. Firstly, it examines the version of the HTTP protocol used to transmit the message. HTTP/1.1 connections are persistent by default, while HTTP/1.0 connections are not. Secondly, it examines the value of the Connection header. The peer can indicate whether it intends to re-use the connection on the opposite side by sending Keep-Alive or Close values in the Connection header. Thirdly, the strategy makes the decision whether the connection is safe to re-use based on the properties of the enclosed entity, if available.
    Connection pools Efficient client-side HTTP transports often requires effective re-use of persistent connections. HttpCore facilitates the process of connection re-use by providing support for managing pools of persistent HTTP connections. Connection pool implementations are thread-safe and can be used concurrently by multiple consumers. By default the pool allows only 20 concurrent connections in total and two concurrent connections per a unique route. The two connection limit is due to the requirements of the HTTP specification. However, in practical terms this can often be too restrictive. One can change the pool configuration at runtime to allow for more concurrent connections depending on a particular application context. future = connpool.lease(target, null); BasicPoolEntry poolEntry = future.get(); HttpClientConnection conn = poolEntry.getConnection(); ]]> Please note that the connection pool has no way of knowing whether or not a leased connection is still being used. It is the responsibility of the connection pool user to ensure that the connection is released back to the pool once it is not longer needed, even if the connection is not reusable. Future future = connpool.lease(target, null); BasicPoolEntry poolEntry = future.get(); try { HttpClientConnection conn = poolEntry.getConnection(); } finally { connpool.release(poolEntry, conn.isOpen()); } ]]> The state of the connection pool can be interrogated at runtime. PoolStats totalStats = connpool.getTotalStats(); System.out.println("total available: " + totalStats.getAvailable()); System.out.println("total leased: " + totalStats.getLeased()); System.out.println("total pending: " + totalStats.getPending()); PoolStats targetStats = connpool.getStats(target); System.out.println("target available: " + targetStats.getAvailable()); System.out.println("target leased: " + targetStats.getLeased()); System.out.println("target pending: " + targetStats.getPending()); ]]> Please note that connection pools do not pro-actively evict expired connections. Even though expired connection cannot be leased to the requester, the pool may accumulate stale connections over time especially after a period of inactivity. It is generally advisable to force eviction of expired and idle connections from the pool after an extensive period of inactivity. connpool.closeExpired(); connpool.closeIdle(1, TimeUnit.MINUTES); ]]>
    TLS/SSL support Blocking connections can be bound to any arbitrary socket. This makes SSL support quite straight-forward. Any SSLSocket instance can be bound to a blocking connection in order to make all messages transmitted over than connection secured by TLS/SSL.
    httpcomponents-core-4.3.2/src/docbkx/resources/0040755 0000000 0000000 00000000000 12276755417 020360 5ustar000000000 0000000 httpcomponents-core-4.3.2/src/docbkx/resources/xsl/0040755 0000000 0000000 00000000000 12276755417 021166 5ustar000000000 0000000 httpcomponents-core-4.3.2/src/docbkx/resources/xsl/html.xsl0100644 0000000 0000000 00000010763 12276755417 022666 0ustar000000000 0000000 html.css 1 0 1 0 book toc 3 1 0 90 0 figure after example before equation before table before procedure before ,

    Authors

    httpcomponents-core-4.3.2/src/docbkx/resources/xsl/html_chunk.xsl0100644 0000000 0000000 00000011722 12276755417 024052 0ustar000000000 0000000 '5' '1' 1 0 1 0 book toc 3 1 1 90 figure after example before equation before table before procedure before ,

    Authors