httpcomponents-core-4.4.4/0040755 0000000 0000000 00000000000 12613460515 014273 5ustar000000000 0000000 httpcomponents-core-4.4.4/LICENSE.txt0100644 0000000 0000000 00000052462 12613456012 016121 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.4.4/README.txt0100644 0000000 0000000 00000004145 12613456023 015771 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.6 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.4.4/BUILDING.txt0100644 0000000 0000000 00000002453 12613456023 016231 0ustar000000000 0000000 Building HttpComponents Core ============================ (1) Requisites -------------- JDK 1.6+ 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) Validating packages Check for binary compatibility with the previous version with: mvn clirr:check Check for proper license headers with: mvn apache-rat:check (5) 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.4.4/NOTICE.txt0100644 0000000 0000000 00000000475 12613456011 016014 0ustar000000000 0000000 Apache HttpComponents Core Copyright 2005-2015 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.4.4/RELEASE_NOTES.txt0100644 0000000 0000000 00000166240 12613456012 017067 0ustar000000000 0000000 Release 4.4.4 ------------------- This is a maintenance release that fixes a number of issues discovered since 4.4.3. Please note that as of 4.4 HttpCore requires Java 1.6 or newer. Changelog ------------------- * [HTTPCORE-410] PoolStats made Serializable Contributed by Oleg Kalnichevski * BufferedHttpEntity to use HttpEntity#writeTo when buffering non-repeatable entities Contributed by Oleg Kalnichevski * Fixed race condition in request initialization code in async client protocol handlers Contributed by Oleg Kalnichevski * Fixed handling of pipelined HEAD requests Contributed by Oleg Kalnichevski * [HTTPCORE-409] NIO HttpServer does not shutdown listener ExecutorService Contributed by Hiranya Jayathilaka Release 4.4.3 ------------------- This is a maintenance release that fixes a regression introduced by release 4.4.2. Please note that as of 4.4 HttpCore requires Java 1.6 or newer. Changelog ------------------- * Fixed regression introduced by HTTPCORE-399. Contributed by Oleg Kalnichevski Release 4.4.2 ------------------- This maintenance release fixes a bug in HTTP request pipelining code discovered after 4.4.1 release. Please note that as of 4.4 HttpCore requires Java 1.6 or newer. Changelog ------------------- * Throw ConnectionClosedException instead of IllegalStateException if an attempt is made to use a closed (not bound to a socket) blocking connection. Contributed by Oleg Kalnichevski * [HTTPCORE-399] Non-blocking client connections incorrectly suspend output causing sequential execution of requests. Contributed by Oleg Kalnichevski Release 4.4.1 ------------------- This maintenance release fixes a number of minor bugs found since 4.4. Please note that as of 4.4 HttpCore requires Java 1.6 or newer. Changelog ------------------- * [HTTPCORE-396]: PrivateKeyStrategy does not work with NIO SSL. Contributed by Oleg Kalnichevski * [HTTPCORE-395]: VersionInfo#getUserAgent reports incorrect Java version. Contributed by Michael Osipov * Non-blocking connection should not trigger end-of-stream callback as long as there is still data in the session input buffer. This can cause a series of short pipelined requests to fail prematurely in case of an unexpected connection termination by the opposite endpoint. Contributed by Oleg Kalnichevski Release 4.4 ----------------- This is the first stable (GA) release of HttpCore 4.4. Notable features included in the 4.4 series are: * Support for pipelined request processing on the server side * Support for pipelined request execution on the client side * Simplified bootstrapping of blocking and non-blocking (NIO) HTTP server implementations * Inclusion of SSL context initialization utilities from HttpClient Please note that as of 4.4 HttpCore requires Java 1.6 or newer. Changelog ------------------- * Performance optimizations Contributed by Dmitry Potapov * Update Apache Commons Logging version from 1.1.3 to 1.2. Contributed by Gary Gregory Release 4.4-BETA1 ------------------- This is the first BETA release from 4.4 release series. Notable features included in the 4.4 series are: * Support for pipelined request processing on the server side * Support for pipelined request execution on the client side * Simplified bootstrapping of blocking and non-blocking (NIO) HTTP server implementations * Inclusion of SSL context initialization utilities from HttpClient * New HTTP element tokenizer implementation Please note that as of 4.4 HttpCore requires Java 1.6 or newer. Release 4.4-ALPHA1 ------------------- This is the first release from the 4.4.x development branch. The most notable features included in this release are: * Support for pipelined request processing on the server side * Support for pipelined request execution on the client side * Simplified bootstrapping of blocking and non-blocking (NIO) HTTP server implementations This release also includes all fixes from the stable 4.2.x release branch. Changelog ------------------- * [HTTPASYNC-77] system resources are not correctly deallocated if I/O reactor is shut down while still inactive (not started) Contributed by Oleg Kalnichevski * [HTTPCORE-377] Allow zero SO_LINGER (immediate abortive close). Contributed by Dmitry Potapov * [HTTPCORE-376] AbstractNIOConnPool#requestCancelled() should not process pending requests wnen being shut down. Contributed by Dmitry Potapov * [HTTPASYNC-69]: async request handler is closed by HttpAsyncRequestExecutor#closed if the underlying connection is found to be in an inconsistent state. Contributed by Oleg Kalnichevski * [HTTPCORE-372] Blocking and non-blocking chunk decoders to throw an I/O exception if data stream is terminated without a closing chunk. Contributed by Dmitry Potapov * [HTTPCORE-368] Customizable buffer management strategies for SSLIOSession. Contributed by offbynull * [HTTPCORE-358] Added I/O reactor listener backlog parameter. Contributed by Dmitry Potapov * [HTTPCORE-357] Avoid DNS lookups in SSLIOSession. Contributed by Oleg Kalnichevski * Update JUnit to version 4.11 from 4.9 Contributed by Gary Gregory 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.3-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.4.4/pom.xml0100644 0000000 0000000 00000031136 12613456023 015610 0ustar000000000 0000000 project org.apache.httpcomponents 7 ../project/pom.xml 4.0.0 httpcomponents-core Apache HttpComponents Core 4.4.4 Apache HttpComponents Core is a library of components for building HTTP enabled services http://hc.apache.org/httpcomponents-core 2005 pom The Apache Software Foundation http://www.apache.org/ Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo Jira http://issues.apache.org/jira/browse/HTTPCORE scm:svn:https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.4.4 scm:svn:https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.4.4 https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.4.4 httpcore httpcore-nio httpcore-osgi httpcore-ab 1.6 1.6 false 4.11 1.8.5 1.2 4.4 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://docs.oracle.com/javase/6/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} org.apache.rat apache-rat-plugin 0.11 verify check src/docbkx/resources/** src/test/resources/*.truststore 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.4.4/httpcore-osgi/0040755 0000000 0000000 00000000000 12613456334 017066 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/pom.xml0100644 0000000 0000000 00000020666 12613456012 020403 0ustar000000000 0000000 4.0.0 org.apache.httpcomponents httpcomponents-core 4.4.4 httpcore-osgi Apache HttpCore OSGi bundle 2005 Apache HttpComponents Core (OSGi bundle) http://hc.apache.org/httpcomponents-core-ga bundle 2.0.0 3.5.0 1.5.4 1.0.1 org.apache.httpcomponents httpcore ${project.version} org.apache.httpcomponents httpcore ${project.version} test-jar test org.apache.httpcomponents httpcore-nio ${project.version} org.ops4j.pax.exam pax-exam-container-native ${pax.exam.version} org.osgi org.osgi.core test org.ops4j.pax.exam pax-exam-junit4 test ${pax.exam.version} org.ops4j.pax.exam pax-exam-link-mvn test ${pax.exam.version} org.ops4j.pax.url pax-url-aether ${pax.url.version} test org.ops4j.pax.url pax-url-wrap ${pax.url.version} test org.osgi org.osgi.core org.slf4j slf4j-api 1.6.4 test ch.qos.logback logback-classic ${logback.version} test ch.qos.logback logback-core ${logback.version} test org.apache.felix org.apache.felix.framework 4.2.0 test org.apache.servicemix.tooling depends-maven-plugin 1.2 generate-depends-file generate-resources generate-depends-file 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.maven.plugins maven-failsafe-plugin ${hc.surefire.version} it integration-test verify **/*IT.class ${project.build.directory} ${project.version} 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 disableOSGiTests disableOSGiTests true org.apache.maven.plugins maven-failsafe-plugin true httpcomponents-core-4.4.4/httpcore-osgi/src/0040755 0000000 0000000 00000000000 12613456012 017646 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/test/0040755 0000000 0000000 00000000000 12613456012 020625 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/0040755 0000000 0000000 00000000000 12613456011 021545 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/org/0040755 0000000 0000000 00000000000 12613456011 022334 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/org/apache/0040755 0000000 0000000 00000000000 12613456011 023555 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/org/apache/http/0040755 0000000 0000000 00000000000 12613456011 024534 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/org/apache/http/osgi/0040755 0000000 0000000 00000000000 12613456012 025476 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/org/apache/http/osgi/Common.java0100644 0000000 0000000 00000010713 12613456012 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.osgi; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.exam.util.PathUtils; import java.io.IOException; import java.net.URL; import java.util.Properties; import static org.ops4j.pax.exam.CoreOptions.bundle; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.wrappedBundle; /** * Test inherit from this. */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class Common { public static String getDependencyVersion(final String groupId, final String artifactId) { final URL depPropsUrl = Common.class.getResource("/META-INF/maven/dependencies.properties"); final Properties depProps = new Properties(); try { depProps.load(depPropsUrl.openStream()); } catch (IOException e) { throw new RuntimeException(e); } String ver = (String) depProps.get(String.format("%s/%s/version", groupId, artifactId)); if (ver == null) { throw new RuntimeException(String.format("No version available for %s:%s", groupId, artifactId)); } ver = ver.replace("-SNAPSHOT", ".SNAPSHOT"); return ver; } @Configuration public static Option[] config() { final String projectVersion = System.getProperty("project.version"); final String buildDir = System.getProperty("project.build.directory", "target"); final String paxLoggingLevel = System.getProperty("bt.osgi.pax.logging.level", "WARN"); return options( bundle(String.format("file:%s/org.apache.httpcomponents.httpcore_%s.jar", buildDir, projectVersion)), wrappedBundle(mavenBundle().groupId("org.apache.httpcomponents") .artifactId("httpcore") .version(projectVersion) .classifier("tests")) .exports("org.apache.http.integration") .imports("org.apache.http.protocol", "org.apache.http", "org.apache.http.config", "org.apache.http.entity", "org.apache.http.impl", "org.apache.http.impl.bootstrap", "org.apache.http.util", "org.apache.http.message", "org.apache.commons.logging; provider=paxlogging", "org.junit"), junitBundles(), systemProperty("pax.exam.osgi.unresolved.fail").value("true"), systemProperty("pax.exam.logging").value("none"), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value(paxLoggingLevel), systemProperty("logback.configurationFile") .value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml") ); } } httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/org/apache/http/osgi/ConcurrentIT.java0100644 0000000 0000000 00000003535 12613456012 030723 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.osgi; import org.apache.http.concurrent.BasicFuture; import org.apache.http.concurrent.FutureCallback; import org.junit.Test; /** * Is the concurrent package to be had? */ public class ConcurrentIT extends Common { @Test public void testCompleted() throws Exception { new BasicFuture(new FutureCallback() { @Override public void completed(final Void result) { // } @Override public void failed(final Exception ex) { // } @Override public void cancelled() { // } }) {}; } } httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/org/apache/http/osgi/ActuallyConnectIT.java0100644 0000000 0000000 00000003375 12613456012 031673 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.osgi; import org.apache.http.integration.TestSyncHttp; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; /** * Use the test methods from TestSyncHttp. */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class ActuallyConnectIT extends TestSyncHttp { @Configuration public static Option[] options() { return Common.config(); } } httpcomponents-core-4.4.4/httpcore-osgi/src/test/java/org/apache/http/osgi/AnnotationIT.java0100644 0000000 0000000 00000002741 12613456012 030711 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.osgi; import org.apache.http.annotation.Immutable; import org.junit.Test; /** * Are the annotations to be had? */ public class AnnotationIT extends Common { @Immutable static class SomeClass { // } @Test public void anything() { new SomeClass(); } } httpcomponents-core-4.4.4/httpcore-osgi/src/test/resources/0040755 0000000 0000000 00000000000 12613456012 022637 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/test/resources/logback.xml0100644 0000000 0000000 00000003002 12613456012 024753 0ustar000000000 0000000 %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n httpcomponents-core-4.4.4/httpcore-osgi/src/main/0040755 0000000 0000000 00000000000 12613456012 020572 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/main/appended-resources/0040755 0000000 0000000 00000000000 12613456012 024362 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/main/appended-resources/META-INF/0040755 0000000 0000000 00000000000 12613456012 025522 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-osgi/src/main/appended-resources/META-INF/NOTICE0100644 0000000 0000000 00000000210 12613456012 026414 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.4.4/httpcore-osgi/src/main/appended-resources/META-INF/LICENSE0100644 0000000 0000000 00000026564 12613456012 026541 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.4.4/httpcore/0040755 0000000 0000000 00000000000 12613456106 016124 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/pom.xml0100644 0000000 0000000 00000012622 12613456022 017436 0ustar000000000 0000000 4.0.0 org.apache.httpcomponents httpcomponents-core 4.4.4 httpcore Apache HttpCore 2005 Apache 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 org.codehaus.mojo build-helper-maven-plugin 1.8 add-source generate-sources add-source src/main/java-deprecated org.apache.rat apache-rat-plugin verify check .externalToolBuilders/** .pmd maven-eclipse.xml org.apache.maven.plugins maven-jar-plugin 2.6 test-jar src/main/resources true **/*.properties maven-javadoc-plugin ${hc.javadoc.version} true ${maven.compiler.source} http://docs.oracle.com/javase/6/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.4.4/httpcore/src/0040755 0000000 0000000 00000000000 12613456022 016710 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/examples/0040755 0000000 0000000 00000000000 12613456022 020526 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/examples/org/0040755 0000000 0000000 00000000000 12613456022 021315 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/examples/org/apache/0040755 0000000 0000000 00000000000 12613456022 022536 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/examples/org/apache/http/0040755 0000000 0000000 00000000000 12613456022 023515 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/examples/org/apache/http/examples/0040755 0000000 0000000 00000000000 12613456022 025333 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/examples/org/apache/http/examples/ElementalReverseProxy.java0100644 0000000 0000000 00000027621 12613456022 032507 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/examples/org/apache/http/examples/ElementalHttpGet.java0100644 0000000 0000000 00000010247 12613456022 031405 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/examples/org/apache/http/examples/ElementalHttpPost.java0100644 0000000 0000000 00000012243 12613456022 031611 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.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(Consts.UTF_8), ContentType.APPLICATION_OCTET_STREAM), new InputStreamEntity( new ByteArrayInputStream( "This is the third test request (will be chunked)" .getBytes(Consts.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.4.4/httpcore/src/examples/org/apache/http/examples/HttpFileServer.java0100644 0000000 0000000 00000016236 12613456022 031111 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.net.SocketTimeoutException; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import org.apache.http.ConnectionClosedException; import org.apache.http.ExceptionLogger; import org.apache.http.HttpConnection; 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.MethodNotSupportedException; import org.apache.http.config.SocketConfig; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.bootstrap.HttpServer; import org.apache.http.impl.bootstrap.ServerBootstrap; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; /** * Embedded HTTP/1.1 file server based on a classic (blocking) I/O model. */ public class HttpFileServer { 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]); } SSLContext sslcontext = null; if (port == 8443) { // Initialize SSL context URL url = HttpFileServer.class.getResource("/my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } sslcontext = SSLContexts.custom() .loadKeyMaterial(url, "secret".toCharArray(), "secret".toCharArray()) .build(); } SocketConfig socketConfig = SocketConfig.custom() .setSoTimeout(15000) .setTcpNoDelay(true) .build(); final HttpServer server = ServerBootstrap.bootstrap() .setListenerPort(port) .setServerInfo("Test/1.1") .setSocketConfig(socketConfig) .setSslContext(sslcontext) .setExceptionLogger(new StdErrorExceptionLogger()) .registerHandler("*", new HttpFileHandler(docRoot)) .create(); server.start(); server.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(5, TimeUnit.SECONDS); } }); } static class StdErrorExceptionLogger implements ExceptionLogger { @Override public void log(final Exception ex) { if (ex instanceof SocketTimeoutException) { System.err.println("Connection timed out"); } else if (ex instanceof ConnectionClosedException) { System.err.println(ex.getMessage()); } else { ex.printStackTrace(); } } } 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.ROOT); 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 { HttpCoreContext coreContext = HttpCoreContext.adapt(context); HttpConnection conn = coreContext.getConnection(HttpConnection.class); response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null)); response.setEntity(body); System.out.println(conn + ": serving file " + file.getPath()); } } } } httpcomponents-core-4.4.4/httpcore/src/examples/org/apache/http/examples/PrintVersionInfo.java0100644 0000000 0000000 00000005507 12613456022 031460 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.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.4.4/httpcore/src/test/0040755 0000000 0000000 00000000000 12613456015 017671 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/0040755 0000000 0000000 00000000000 12613456013 020610 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/0040755 0000000 0000000 00000000000 12613456013 021377 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/0040755 0000000 0000000 00000000000 12613456013 022620 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/0040755 0000000 0000000 00000000000 12613456015 023601 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/TestHttpHost.java0100644 0000000 0000000 00000024705 12613456015 027066 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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("127.0.0.1", new byte[] {127,0,0,1}), 80, "http"); final HttpHost host8 = new HttpHost("127.0.0.1", 80, "http"); final HttpHost host9 = new HttpHost( InetAddress.getByAddress("somehost",new byte[] {127,0,0,1}), 80, "http"); final HttpHost host10 = new HttpHost( InetAddress.getByAddress(new byte[] {127,0,0,1}), "somehost", 80, "http"); final HttpHost host11 = new HttpHost( InetAddress.getByAddress("someotherhost",new byte[] {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()); Assert.assertTrue(host8.hashCode() != host9.hashCode()); Assert.assertTrue(host9.hashCode() == host10.hashCode()); Assert.assertTrue(host10.hashCode() != host11.hashCode()); Assert.assertTrue(host9.hashCode() != host11.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("127.0.0.1", new byte[] {127,0,0,1}), 80, "http"); final HttpHost host8 = new HttpHost("127.0.0.1", 80, "http"); final HttpHost host9 = new HttpHost( InetAddress.getByAddress("somehost", new byte[] {127,0,0,1}), 80, "http"); final HttpHost host10 = new HttpHost( InetAddress.getByAddress(new byte[] {127,0,0,1}), "somehost", 80, "http"); final HttpHost host11 = new HttpHost( InetAddress.getByAddress("someotherhost",new byte[] {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.assertFalse(host7.equals(host8)); Assert.assertTrue(!host7.equals(host9)); Assert.assertFalse(host1.equals(null)); Assert.assertFalse(host1.equals("http://somehost")); Assert.assertFalse(host9.equals("http://somehost")); Assert.assertFalse(host8.equals(host9)); Assert.assertTrue(host9.equals(host10)); Assert.assertFalse(host9.equals(host11)); } @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("127.0.0.1", new byte[] {127,0,0,1}), 80, "http"); Assert.assertEquals("http://127.0.0.1:80", host7.toString()); final HttpHost host9 = new HttpHost( InetAddress.getByAddress("somehost", new byte[] {127,0,0,1}), 80, "http"); Assert.assertEquals("http://somehost:80", host9.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); } @Test public void testCreateFromString() throws Exception { Assert.assertEquals(new HttpHost("somehost", 8080, "https"), HttpHost.create("https://somehost:8080")); Assert.assertEquals(new HttpHost("somehost", 8080, "https"), HttpHost.create("HttpS://SomeHost:8080")); Assert.assertEquals(new HttpHost("somehost", 1234, null), HttpHost.create("somehost:1234")); Assert.assertEquals(new HttpHost("somehost", -1, null), HttpHost.create("somehost")); } @Test public void testCreateFromStringInvalid() throws Exception { try { HttpHost.create(null); Assert.fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) { } try { HttpHost.create(" host "); Assert.fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) { } try { HttpHost.create("host :8080"); Assert.fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) { } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/TestHttpExceptions.java0100644 0000000 0000000 00000003673 12613456013 030271 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/TestHttpVersion.java0100644 0000000 0000000 00000012050 12613456014 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; 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.4.4/httpcore/src/test/java/org/apache/http/message/0040755 0000000 0000000 00000000000 12613456014 025224 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000145 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicTokenIterator.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicTokenIterator.java0100644 0000000 0000000 00000026020 12613456014 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.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.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 00000000154 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderValueFormatter.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderValueFormatt0100644 0000000 0000000 00000021374 12613456014 032477 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicLineParser.java0100644 0000000 0000000 00000030576 12613456014 031745 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/message/TestHeaderGroup.java0100644 0000000 0000000 00000022026 12613456014 031133 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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()); } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestTokenParser.java0100644 0000000 0000000 00000016656 12613456014 031177 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.util.CharArrayBuffer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestTokenParser { private TokenParser parser; @Before public void setUp() throws Exception { parser = new TokenParser(); } private static CharArrayBuffer createBuffer(final String value) { if (value == null) { return null; } final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); return buffer; } @Test public void testBasicTokenParsing() throws Exception { final String s = " raw: \" some stuff \""; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); parser.skipWhiteSpace(raw, cursor); Assert.assertFalse(cursor.atEnd()); Assert.assertEquals(3, cursor.getPos()); final StringBuilder strbuf1 = new StringBuilder(); parser.copyContent(raw, cursor, TokenParser.INIT_BITSET(':'), strbuf1); Assert.assertFalse(cursor.atEnd()); Assert.assertEquals(6, cursor.getPos()); Assert.assertEquals("raw", strbuf1.toString()); Assert.assertEquals(':', raw.charAt(cursor.getPos())); cursor.updatePos(cursor.getPos() + 1); parser.skipWhiteSpace(raw, cursor); Assert.assertFalse(cursor.atEnd()); Assert.assertEquals(8, cursor.getPos()); final StringBuilder strbuf2 = new StringBuilder(); parser.copyQuotedContent(raw, cursor, strbuf2); Assert.assertTrue(cursor.atEnd()); Assert.assertEquals(" some stuff ", strbuf2.toString()); parser.copyQuotedContent(raw, cursor, strbuf2); Assert.assertTrue(cursor.atEnd()); parser.skipWhiteSpace(raw, cursor); Assert.assertTrue(cursor.atEnd()); } @Test public void testTokenParsingWithQuotedPairs() throws Exception { final String s = "raw: \"\\\"some\\stuff\\\\\""; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); parser.skipWhiteSpace(raw, cursor); Assert.assertFalse(cursor.atEnd()); Assert.assertEquals(0, cursor.getPos()); final StringBuilder strbuf1 = new StringBuilder(); parser.copyContent(raw, cursor, TokenParser.INIT_BITSET(':'), strbuf1); Assert.assertFalse(cursor.atEnd()); Assert.assertEquals("raw", strbuf1.toString()); Assert.assertEquals(':', raw.charAt(cursor.getPos())); cursor.updatePos(cursor.getPos() + 1); parser.skipWhiteSpace(raw, cursor); Assert.assertFalse(cursor.atEnd()); final StringBuilder strbuf2 = new StringBuilder(); parser.copyQuotedContent(raw, cursor, strbuf2); Assert.assertTrue(cursor.atEnd()); Assert.assertEquals("\"some\\stuff\\", strbuf2.toString()); } @Test public void testTokenParsingIncompleteQuote() throws Exception { final String s = "\"stuff and more stuff "; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final StringBuilder strbuf1 = new StringBuilder(); parser.copyQuotedContent(raw, cursor, strbuf1); Assert.assertEquals("stuff and more stuff ", strbuf1.toString()); } @Test public void testTokenParsingTokensWithUnquotedBlanks() throws Exception { final String s = " stuff and \tsome\tmore stuff ;"; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final String result = parser.parseToken(raw, cursor, TokenParser.INIT_BITSET(';')); Assert.assertEquals("stuff and some more stuff", result); } @Test public void testTokenParsingMixedValuesAndQuotedValues() throws Exception { final String s = " stuff and \" some more \" \"stuff ;"; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final String result = parser.parseValue(raw, cursor, TokenParser.INIT_BITSET(';')); Assert.assertEquals("stuff and some more stuff ;", result); } @Test public void testTokenParsingMixedValuesAndQuotedValues2() throws Exception { final String s = "stuff\"more\"stuff;"; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final String result = parser.parseValue(raw, cursor, TokenParser.INIT_BITSET(';')); Assert.assertEquals("stuffmorestuff", result); } @Test public void testTokenParsingEscapedQuotes() throws Exception { final String s = "stuff\"\\\"more\\\"\"stuff;"; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final String result = parser.parseValue(raw, cursor, TokenParser.INIT_BITSET(';')); Assert.assertEquals("stuff\"more\"stuff", result); } @Test public void testTokenParsingEscapedDelimiter() throws Exception { final String s = "stuff\"\\\"more\\\";\"stuff;"; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final String result = parser.parseValue(raw, cursor, TokenParser.INIT_BITSET(';')); Assert.assertEquals("stuff\"more\";stuff", result); } @Test public void testTokenParsingEscapedSlash() throws Exception { final String s = "stuff\"\\\"more\\\";\\\\\"stuff;"; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final String result = parser.parseValue(raw, cursor, TokenParser.INIT_BITSET(';')); Assert.assertEquals("stuff\"more\";\\stuff", result); } @Test public void testTokenParsingSlashOutsideQuotes() throws Exception { final String s = "stuff\\; more stuff;"; final CharArrayBuffer raw = createBuffer(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final String result = parser.parseValue(raw, cursor, TokenParser.INIT_BITSET(';')); Assert.assertEquals("stuff\\", result); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestHeader.java0100644 0000000 0000000 00000011013 12613456014 030110 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 00000000155 12613460515 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderElementIterator.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderElementItera0100644 0000000 0000000 00000011366 12613456014 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.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 } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicMessages.java0100644 0000000 0000000 00000016315 12613456014 031443 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/message/TestHeaderElement.java0100644 0000000 0000000 00000015745 12613456014 031442 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } } ././@LongLink0100644 0000000 0000000 00000000151 12613460515 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderValueParser.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicHeaderValueParser.0100644 0000000 0000000 00000034646 12613456014 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.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 1615886 2014-08-05 08:16:24Z olegk $ */ 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 00000000145 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicLineFormatter.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicLineFormatter.java0100644 0000000 0000000 00000013242 12613456014 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.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.4.4/httpcore/src/test/java/org/apache/http/message/TestNameValuePair.java0100644 0000000 0000000 00000006712 12613456014 031423 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/message/TestBasicHttpResponse.java0100644 0000000 0000000 00000011360 12613456014 032325 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/message/TestAbstractMessage.java0100644 0000000 0000000 00000011446 12613456014 032002 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override 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.4.4/httpcore/src/test/java/org/apache/http/message/TestStatusLine.java0100644 0000000 0000000 00000010402 12613456014 031014 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/message/TestRequestLine.java0100644 0000000 0000000 00000007667 12613456014 031204 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.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.4.4/httpcore/src/test/java/org/apache/http/message/TestBufferedHeader.java0100644 0000000 0000000 00000010507 12613456014 031562 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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()); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/concurrent/0040755 0000000 0000000 00000000000 12613456014 025762 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/concurrent/TestBasicFuture.java0100644 0000000 0000000 00000017263 12613456014 031707 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/concurrent/BasicFutureCallback.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/concurrent/BasicFutureCallback.java0100644 0000000 0000000 00000004054 12613456014 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.concurrent; class BasicFutureCallback implements FutureCallback { private T result; private Exception ex; private boolean completed; private boolean failed; private boolean cancelled; @Override public void completed(final T result) { this.result = result; this.completed = true; } public T getResult() { return this.result; } public Exception getException() { return this.ex; } @Override public void failed(final Exception ex) { this.ex = ex; this.failed = true; } @Override 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.4.4/httpcore/src/test/java/org/apache/http/protocol/0040755 0000000 0000000 00000000000 12613456014 025441 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000147 12613460515 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestHttpRequestExecutor.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestHttpRequestExecutor.ja0100644 0000000 0000000 00000050727 12613456014 032634 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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()); } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestChainBuilder.java0100644 0000000 0000000 00000005100 12613456014 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.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)); } } ././@LongLink0100644 0000000 0000000 00000000157 12613460515 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestUriHttpRequestHandlerMapper.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestUriHttpRequestHandlerM0100644 0000000 0000000 00000007727 12613456014 032621 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } } ././@LongLink0100644 0000000 0000000 00000000150 12613460515 011632 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestHttpExecutionContext.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestHttpExecutionContext.j0100644 0000000 0000000 00000007723 12613456014 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 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 } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestHttpService.java0100644 0000000 0000000 00000074452 12613456014 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.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 testExecutionEntityEnclosingRequest() 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 testExecutionEntityEnclosingRequestWithExpectContinue() 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 testExecutionEntityEnclosingRequestCustomExpectationVerifier() 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() { @Override 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(); } @Test public void testNoContentResponse() 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, HttpStatus.SC_NO_CONTENT, "No Content"); 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.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Mockito.verify(httprocessor).process(response, context); Mockito.verify(requestHandler).handle(request, response, context); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn, Mockito.never()).sendResponseEntity(Mockito.any()); Mockito.verify(conn).flush(); Mockito.verify(conn, Mockito.never()).close(); } @Test public void testResponseToHead() 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("HEAD", "/"); 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.assertSame(conn, context.getConnection()); Assert.assertSame(request, context.getRequest()); Mockito.verify(httprocessor).process(response, context); Mockito.verify(requestHandler).handle(request, response, context); Mockito.verify(conn).sendResponseHeader(response); Mockito.verify(conn, Mockito.never()).sendResponseEntity(Mockito.any()); Mockito.verify(conn).flush(); Mockito.verify(conn, Mockito.never()).close(); } } ././@LongLink0100644 0000000 0000000 00000000150 12613460515 011632 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestStandardInterceptors.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestStandardInterceptors.j0100644 0000000 0000000 00000133543 12613456014 032624 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestUriPatternMatcher.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/protocol/TestUriPatternMatcher.java0100644 0000000 0000000 00000011654 12613456014 032551 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/ssl/0040755 0000000 0000000 00000000000 12613456014 024401 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/ssl/TestSSLContextBuilder.java0100644 0000000 0000000 00000066624 12613456014 031434 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.ssl; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.security.KeyStore; import java.security.Principal; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import org.junit.After; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link org.apache.http.ssl.SSLContextBuilder}. */ public class TestSSLContextBuilder { private ExecutorService executorService; @After public void cleanup() throws Exception { if (this.executorService != null) { this.executorService.shutdown(); this.executorService.awaitTermination(5, TimeUnit.SECONDS); } } @Test public void testBuildDefault() throws Exception { new SSLContextBuilder().build(); } @Test public void testBuildAllNull() throws Exception { final SSLContext sslContext = SSLContextBuilder.create() .useProtocol(null) .setSecureRandom(null) .loadTrustMaterial((KeyStore) null, null) .loadKeyMaterial((KeyStore) null, null, null) .build(); Assert.assertNotNull(sslContext); Assert.assertEquals("TLS", sslContext.getProtocol()); } @Test public void testKeyWithAlternatePassword() throws Exception { final URL resource1 = getClass().getResource("/test-keypasswd.keystore"); final String storePassword = "nopassword"; final String keyPassword = "password"; final SSLContext sslContext = SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .loadTrustMaterial(resource1, storePassword.toCharArray()) .build(); Assert.assertNotNull(sslContext); final SSLSocketFactory socketFactory = sslContext.getSocketFactory(); Assert.assertNotNull(socketFactory); } @Test(expected=UnrecoverableKeyException.class) public void testKeyWithAlternatePasswordInvalid() throws Exception { final URL resource1 = getClass().getResource("/test-keypasswd.keystore"); final String storePassword = "nopassword"; final String keyPassword = "!password"; SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .loadTrustMaterial(resource1, storePassword.toCharArray()) .build(); } @Test public void testSSLHanskshakeServerTrusted() throws Exception { final URL resource1 = getClass().getResource("/test.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource1, storePassword.toCharArray()) .build(); Assert.assertNotNull(clientSslContext); final ServerSocket serverSocket = serverSslContext.getServerSocketFactory().createServerSocket(); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); final Future future = this.executorService.submit(new Callable() { @Override public Boolean call() throws Exception { final Socket socket = serverSocket.accept(); try { final OutputStream outputStream = socket.getOutputStream(); outputStream.write(new byte[]{'H', 'i'}); outputStream.flush(); } finally { socket.close(); } return Boolean.TRUE; } }); final int localPort = serverSocket.getLocalPort(); final Socket clientSocket = clientSslContext.getSocketFactory().createSocket(); try { clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); final InputStream inputStream = clientSocket.getInputStream(); Assert.assertEquals('H', inputStream.read()); Assert.assertEquals('i', inputStream.read()); Assert.assertEquals(-1, inputStream.read()); } finally { clientSocket.close(); } final Boolean result = future.get(5, TimeUnit.SECONDS); Assert.assertNotNull(result); } @Test(expected = IOException.class) public void testSSLHanskshakeServerNotTrusted() throws Exception { final URL resource1 = getClass().getResource("/test-server.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final URL resource2 = getClass().getResource("/test.keystore"); final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource2, storePassword.toCharArray()) .build(); Assert.assertNotNull(clientSslContext); final ServerSocket serverSocket = serverSslContext.getServerSocketFactory().createServerSocket(); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); this.executorService.submit(new Callable() { @Override public Boolean call() throws Exception { final SSLSocket socket = (SSLSocket) serverSocket.accept(); try { socket.getSession(); } finally { socket.close(); } return Boolean.FALSE; } }); final int localPort = serverSocket.getLocalPort(); final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); try { clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); clientSocket.startHandshake(); } finally { clientSocket.close(); } } @Test public void testSSLHanskshakeServerCustomTrustStrategy() throws Exception { final URL resource1 = getClass().getResource("/test-server.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final AtomicReference certChainRef = new AtomicReference(); final TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { certChainRef.set(chain); return true; } }; final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(trustStrategy) .build(); Assert.assertNotNull(clientSslContext); final ServerSocket serverSocket = serverSslContext.getServerSocketFactory().createServerSocket(); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); final Future future = this.executorService.submit(new Callable() { @Override public Boolean call() throws Exception { final Socket socket = serverSocket.accept(); try { final OutputStream outputStream = socket.getOutputStream(); outputStream.write(new byte[]{'H', 'i'}); outputStream.flush(); } finally { socket.close(); } return Boolean.TRUE; } }); final int localPort = serverSocket.getLocalPort(); final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); try { clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); final InputStream inputStream = clientSocket.getInputStream(); Assert.assertEquals('H', inputStream.read()); Assert.assertEquals('i', inputStream.read()); Assert.assertEquals(-1, inputStream.read()); } finally { clientSocket.close(); } final Boolean result = future.get(5, TimeUnit.SECONDS); Assert.assertNotNull(result); final X509Certificate[] certs = certChainRef.get(); Assert.assertNotNull(certs); Assert.assertEquals(2, certs.length); final X509Certificate cert1 = certs[0]; final Principal subjectDN1 = cert1.getSubjectDN(); Assert.assertNotNull(subjectDN1); Assert.assertEquals("CN=Test Server, OU=HttpComponents Project, O=Apache Software Foundation, " + "L=Unknown, ST=Unknown, C=Unknown", subjectDN1.getName()); final X509Certificate cert2 = certs[1]; final Principal subjectDN2 = cert2.getSubjectDN(); Assert.assertNotNull(subjectDN2); Assert.assertEquals("EMAILADDRESS=dev@hc.apache.org, " + "CN=Test CA, OU=HttpComponents Project, O=Apache Software Foundation", subjectDN2.getName()); final Principal issuerDN = cert2.getIssuerDN(); Assert.assertNotNull(issuerDN); Assert.assertEquals("EMAILADDRESS=dev@hc.apache.org, " + "CN=Test CA, OU=HttpComponents Project, O=Apache Software Foundation", issuerDN.getName()); } @Test public void testSSLHanskshakeClientUnauthenticated() throws Exception { final URL resource1 = getClass().getResource("/test-server.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final URL resource2 = getClass().getResource("/test-client.keystore"); final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource2, storePassword.toCharArray()) .build(); Assert.assertNotNull(clientSslContext); final SSLServerSocket serverSocket = (SSLServerSocket) serverSslContext.getServerSocketFactory().createServerSocket(); serverSocket.setWantClientAuth(true); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); final Future future = this.executorService.submit(new Callable() { @Override public Principal call() throws Exception { final SSLSocket socket = (SSLSocket) serverSocket.accept(); Principal clientPrincipal = null; try { final SSLSession session = socket.getSession(); try { clientPrincipal = session.getPeerPrincipal(); } catch (SSLPeerUnverifiedException ignore) { } final OutputStream outputStream = socket.getOutputStream(); outputStream.write(new byte [] {'H', 'i'}); outputStream.flush(); } finally { socket.close(); } return clientPrincipal; } }); final int localPort = serverSocket.getLocalPort(); final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); try { clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); clientSocket.startHandshake(); final InputStream inputStream = clientSocket.getInputStream(); Assert.assertEquals('H', inputStream.read()); Assert.assertEquals('i', inputStream.read()); Assert.assertEquals(-1, inputStream.read()); } finally { clientSocket.close(); } final Principal clientPrincipal = future.get(5, TimeUnit.SECONDS); Assert.assertNull(clientPrincipal); } @Test(expected = IOException.class) public void testSSLHanskshakeClientUnauthenticatedError() throws Exception { final URL resource1 = getClass().getResource("/test-server.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final URL resource2 = getClass().getResource("/test-client.keystore"); final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource2, storePassword.toCharArray()) .build(); Assert.assertNotNull(clientSslContext); final SSLServerSocket serverSocket = (SSLServerSocket) serverSslContext.getServerSocketFactory().createServerSocket(); serverSocket.setNeedClientAuth(true); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); this.executorService.submit(new Callable() { @Override public Boolean call() throws Exception { final SSLSocket socket = (SSLSocket) serverSocket.accept(); try { socket.getSession(); } finally { socket.close(); } return Boolean.FALSE; } }); final int localPort = serverSocket.getLocalPort(); final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); try { clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); clientSocket.startHandshake(); } finally { clientSocket.close(); } } @Test public void testSSLHanskshakeClientAuthenticated() throws Exception { final URL resource1 = getClass().getResource("/test-server.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource1, storePassword.toCharArray()) .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final URL resource2 = getClass().getResource("/test-client.keystore"); final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource2, storePassword.toCharArray()) .loadKeyMaterial(resource2, storePassword.toCharArray(), storePassword.toCharArray()) .build(); Assert.assertNotNull(clientSslContext); final SSLServerSocket serverSocket = (SSLServerSocket) serverSslContext.getServerSocketFactory().createServerSocket(); serverSocket.setNeedClientAuth(true); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); final Future future = this.executorService.submit(new Callable() { @Override public Principal call() throws Exception { final SSLSocket socket = (SSLSocket) serverSocket.accept(); try { final SSLSession session = socket.getSession(); final Principal clientPrincipal = session.getPeerPrincipal(); final OutputStream outputStream = socket.getOutputStream(); outputStream.write(new byte[]{'H', 'i'}); outputStream.flush(); return clientPrincipal; } finally { socket.close(); } } }); final int localPort = serverSocket.getLocalPort(); final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); try { clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); clientSocket.startHandshake(); final InputStream inputStream = clientSocket.getInputStream(); Assert.assertEquals('H', inputStream.read()); Assert.assertEquals('i', inputStream.read()); Assert.assertEquals(-1, inputStream.read()); } finally { clientSocket.close(); } final Principal clientPrincipal = future.get(5, TimeUnit.SECONDS); Assert.assertNotNull(clientPrincipal); } @Test public void testSSLHanskshakeClientAuthenticatedPrivateKeyStrategy() throws Exception { final URL resource1 = getClass().getResource("/test-server.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource1, storePassword.toCharArray()) .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final PrivateKeyStrategy privateKeyStrategy = new PrivateKeyStrategy() { @Override public String chooseAlias(final Map aliases, final Socket socket) { if (aliases.keySet().contains("client2")) { return "client2"; } else { return null; } } }; final URL resource2 = getClass().getResource("/test-client.keystore"); final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource2, storePassword.toCharArray()) .loadKeyMaterial(resource2, storePassword.toCharArray(), storePassword.toCharArray(), privateKeyStrategy) .build(); Assert.assertNotNull(clientSslContext); final SSLServerSocket serverSocket = (SSLServerSocket) serverSslContext.getServerSocketFactory().createServerSocket(); serverSocket.setNeedClientAuth(true); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); final Future future = this.executorService.submit(new Callable() { @Override public Principal call() throws Exception { final SSLSocket socket = (SSLSocket) serverSocket.accept(); try { final SSLSession session = socket.getSession(); final Principal clientPrincipal = session.getPeerPrincipal(); final OutputStream outputStream = socket.getOutputStream(); outputStream.write(new byte[]{'H', 'i'}); outputStream.flush(); return clientPrincipal; } finally { socket.close(); } } }); final int localPort = serverSocket.getLocalPort(); final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); try { clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); clientSocket.startHandshake(); final InputStream inputStream = clientSocket.getInputStream(); Assert.assertEquals('H', inputStream.read()); Assert.assertEquals('i', inputStream.read()); Assert.assertEquals(-1, inputStream.read()); } finally { clientSocket.close(); } final Principal clientPrincipal = future.get(5, TimeUnit.SECONDS); Assert.assertNotNull(clientPrincipal); Assert.assertEquals("CN=Test Client 2,OU=HttpComponents Project,O=Apache Software Foundation," + "L=Unknown,ST=Unknown,C=Unknown", clientPrincipal.getName()); } @Test(expected = IOException.class) public void testSSLHanskshakeProtocolMismatch1() throws Exception { final URL resource1 = getClass().getResource("/test-server.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final URL resource2 = getClass().getResource("/test-client.keystore"); final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource2, storePassword.toCharArray()) .build(); Assert.assertNotNull(clientSslContext); final SSLServerSocket serverSocket = (SSLServerSocket) serverSslContext.getServerSocketFactory().createServerSocket(); final Set supportedServerProtocols = new LinkedHashSet(Arrays.asList(serverSocket.getSupportedProtocols())); Assert.assertTrue(supportedServerProtocols.contains("TLSv1")); serverSocket.setEnabledProtocols(new String[] {"TLSv1"}); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); this.executorService.submit(new Callable() { @Override public Boolean call() throws Exception { final SSLSocket socket = (SSLSocket) serverSocket.accept(); try { socket.getSession(); } finally { socket.close(); } return Boolean.FALSE; } }); final int localPort = serverSocket.getLocalPort(); final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); try { final Set supportedClientProtocols = new LinkedHashSet(Arrays.asList(clientSocket.getSupportedProtocols())); Assert.assertTrue(supportedClientProtocols.contains("SSLv3")); clientSocket.setEnabledProtocols(new String[] {"SSLv3"} ); clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); clientSocket.startHandshake(); } finally { clientSocket.close(); } } @Test(expected = SSLHandshakeException.class) public void testSSLHanskshakeProtocolMismatch2() throws Exception { final URL resource1 = getClass().getResource("/test-server.keystore"); final String storePassword = "nopassword"; final String keyPassword = "nopassword"; final SSLContext serverSslContext = SSLContextBuilder.create() .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray()) .build(); Assert.assertNotNull(serverSslContext); final URL resource2 = getClass().getResource("/test-client.keystore"); final SSLContext clientSslContext = SSLContextBuilder.create() .loadTrustMaterial(resource2, storePassword.toCharArray()) .build(); Assert.assertNotNull(clientSslContext); final SSLServerSocket serverSocket = (SSLServerSocket) serverSslContext.getServerSocketFactory().createServerSocket(); final Set supportedServerProtocols = new LinkedHashSet(Arrays.asList(serverSocket.getSupportedProtocols())); Assert.assertTrue(supportedServerProtocols.contains("SSLv3")); serverSocket.setEnabledProtocols(new String[] {"SSLv3"}); serverSocket.bind(new InetSocketAddress(0)); this.executorService = Executors.newSingleThreadExecutor(); this.executorService.submit(new Callable() { @Override public Boolean call() throws Exception { final SSLSocket socket = (SSLSocket) serverSocket.accept(); try { socket.getSession(); } finally { socket.close(); } return Boolean.FALSE; } }); final int localPort = serverSocket.getLocalPort(); final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); try { final Set supportedClientProtocols = new LinkedHashSet(Arrays.asList(clientSocket.getSupportedProtocols())); Assert.assertTrue(supportedClientProtocols.contains("TLSv1")); clientSocket.setEnabledProtocols(new String[] {"TLSv1"}); clientSocket.connect(new InetSocketAddress("localhost", localPort), 5000); clientSocket.startHandshake(); } finally { clientSocket.close(); } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/pool/0040755 0000000 0000000 00000000000 12613456015 024552 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/pool/TestRouteSpecificPool.java0100644 0000000 0000000 00000031205 12613456015 031651 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/pool/TestConnPool.java0100644 0000000 0000000 00000102311 12613456015 027777 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.Collections; 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); } @Override protected boolean validate(final LocalPoolEntry entry) { return !entry.getConnection().isStale(); } } @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()); Assert.assertEquals(Collections.emptySet(), pool.getRoutes()); 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()); Assert.assertEquals(Collections.singleton("somehost"), pool.getRoutes()); 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); } @Test public void testValidateConnectionNotStale() throws Exception { final HttpConnection conn = Mockito.mock(HttpConnection.class); Mockito.when(conn.isOpen()).thenReturn(true); Mockito.when(conn.isStale()).thenReturn(false); final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); pool.setValidateAfterInactivity(5); final Future future1 = pool.lease("somehost", null); final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry1); pool.release(entry1, true); Thread.sleep(10); final Future future2 = pool.lease("somehost", null); final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry2); Assert.assertSame(entry1, entry2); Mockito.verify(conn, Mockito.times(1)).isStale(); } @Test public void testValidateConnectionStale() throws Exception { final HttpConnection conn = Mockito.mock(HttpConnection.class); Mockito.when(conn.isOpen()).thenReturn(true); Mockito.when(conn.isStale()).thenReturn(false); final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class); Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn); final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10); pool.setValidateAfterInactivity(5); final Future future1 = pool.lease("somehost", null); final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry1); pool.release(entry1, true); Thread.sleep(10); Mockito.verify(connFactory, Mockito.times(1)).create("somehost"); Mockito.when(conn.isStale()).thenReturn(true); final Future future2 = pool.lease("somehost", null); final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS); Assert.assertNotNull(entry2); Assert.assertNotSame(entry1, entry2); Mockito.verify(conn, Mockito.times(1)).isStale(); Mockito.verify(conn, Mockito.times(1)).close(); Mockito.verify(connFactory, Mockito.times(2)).create("somehost"); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/pool/TestPoolEntry.java0100644 0000000 0000000 00000011631 12613456015 030207 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.getValidityDeadline(), entry1.getExpiry()); Assert.assertEquals(entry1.getCreated() + 10L, entry1.getValidityDeadline()); } @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.getValidityDeadline()); Assert.assertEquals(entry1.getValidityDeadline(), 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.4.4/httpcore/src/test/java/org/apache/http/config/0040755 0000000 0000000 00000000000 12613456014 025045 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/config/TestRegistry.java0100644 0000000 0000000 00000003241 12613456014 030355 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/util/0040755 0000000 0000000 00000000000 12613456015 024556 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/util/TestCharArrayBuffer.java0100644 0000000 0000000 00000036103 12613456015 031267 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.apache.http.Consts; 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(Consts.ASCII); final byte[] b2 = s2.getBytes(Consts.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]); } @Test public void testSubSequenceIndexOfOutBound() { final CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append("stuff"); try { buffer.subSequence(-2, 10); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.subSequence(12, 10); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } try { buffer.subSequence(2, 1); Assert.fail("IndexOutOfBoundsException should have been thrown"); } catch (final IndexOutOfBoundsException ex) { // expected } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/util/TestEntityUtils.java0100644 0000000 0000000 00000022042 12613456015 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.util; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.Charset; import org.apache.http.Consts; 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(Consts.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(Consts.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(Consts.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(Consts.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(Consts.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(Consts.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(Consts.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(Charset.forName("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(Consts.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); } @Test public void testContentWithInvalidContentTypeToString() 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=nosuchcharset")); final String s = EntityUtils.toString(httpentity, "UTF-8"); Assert.assertEquals(content, s); } /** * Helper class that returns {@code 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 {@code null} */ @Override public InputStream getContent() { return null; } } // class NullEntity } // class TestEntityUtils httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/util/TestTextUtils.java0100644 0000000 0000000 00000004305 12613456015 030225 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 org.apache.http.util.TextUtils}. * */ public class TestTextUtils { @Test public void testTextEmpty() { Assert.assertTrue(TextUtils.isEmpty(null)); Assert.assertTrue(TextUtils.isEmpty("")); Assert.assertFalse(TextUtils.isEmpty("\t")); } @Test public void testTextBlank() { Assert.assertTrue(TextUtils.isBlank(null)); Assert.assertTrue(TextUtils.isBlank("")); Assert.assertTrue(TextUtils.isBlank(" ")); Assert.assertTrue(TextUtils.isBlank("\t")); } @Test public void testTextContainsBlanks() { Assert.assertFalse(TextUtils.containsBlanks(null)); Assert.assertFalse(TextUtils.containsBlanks("")); Assert.assertTrue(TextUtils.containsBlanks(" ")); Assert.assertTrue(TextUtils.containsBlanks("\t")); Assert.assertTrue(TextUtils.containsBlanks(" a")); Assert.assertFalse(TextUtils.containsBlanks("a")); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/util/TestEncodingUtils.java0100644 0000000 0000000 00000014707 12613456015 031036 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/util/TestArgs.java0100644 0000000 0000000 00000011412 12613456015 027151 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/util/TestByteArrayBuffer.java0100644 0000000 0000000 00000026140 12613456015 031315 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.apache.http.Consts; 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(Consts.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.4.4/httpcore/src/test/java/org/apache/http/util/TestLangUtils.java0100644 0000000 0000000 00000006437 12613456015 030172 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/util/TestAsserts.java0100644 0000000 0000000 00000004610 12613456015 027703 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/impl/0040755 0000000 0000000 00000000000 12613456014 024541 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestBHttpConnectionBase.java0100644 0000000 0000000 00000035152 12613456014 032103 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 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.Assert; 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(1)).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 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestDefaultBHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestDefaultBHttpClientConnecti0100644 0000000 0000000 00000014752 12613456013 032501 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 org.apache.http.Consts; 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; import org.junit.Assert; 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(Consts.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(Consts.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 00000000154 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestDefaultBHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestDefaultBHttpServerConnecti0100644 0000000 0000000 00000016376 12613456014 032536 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 org.apache.http.Consts; 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; import org.junit.Assert; 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(Consts.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(Consts.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); } } ././@LongLink0100644 0000000 0000000 00000000152 12613460515 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestEnglishReasonPhraseCatalog.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestEnglishReasonPhraseCatalog0100644 0000000 0000000 00000006320 12613456013 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; 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); } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/SessionInputBufferMock.java0100644 0000000 0000000 00000010003 12613456013 032001 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.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 MessageConstraints constrains, final Charset charset) { this(bytes, BUFFER_SIZE, constrains, charset != null ? charset.newDecoder() : null); } public SessionInputBufferMock( final byte[] bytes, final Charset charset) { this(bytes, null, charset); } public SessionInputBufferMock( final byte[] bytes, final CharsetDecoder decoder) { this(bytes, BUFFER_SIZE, null, decoder); } public SessionInputBufferMock( final String s, final MessageConstraints constrains, final Charset charset) { this(s.getBytes(charset), constrains, charset); } public SessionInputBufferMock( final String s, final Charset charset) { this(s.getBytes(charset), MessageConstraints.DEFAULT, charset); } @Override public boolean isDataAvailable(final int timeout) throws IOException { return true; } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestBasicRequest.java0100644 0000000 0000000 00000004654 12613456014 030644 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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()); } } ././@LongLink0100644 0000000 0000000 00000000151 12613460515 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestNoConnectionReuseStrategy.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestNoConnectionReuseStrategy.0100644 0000000 0000000 00000003537 12613456013 032531 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460515 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestDefaultConnectionReuseStrategy.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/TestDefaultConnectionReuseStra0100644 0000000 0000000 00000025050 12613456014 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.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.4.4/httpcore/src/test/java/org/apache/http/impl/SessionOutputBufferMock.java0100644 0000000 0000000 00000005673 12613456013 032223 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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[] {}; } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/pool/0040755 0000000 0000000 00000000000 12613456013 025511 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/pool/TestBasicConnPool.java0100644 0000000 0000000 00000010001 12613456013 031672 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/impl/io/0040755 0000000 0000000 00000000000 12613456013 025147 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000154 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestContentLengthOutputStream.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestContentLengthOutputStre0100644 0000000 0000000 00000007047 12613456013 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.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 00000000152 12613460515 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TimeoutByteArrayInputStream.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TimeoutByteArrayInputStream0100644 0000000 0000000 00000007257 12613456013 032547 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 00000000146 12613460515 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestSessionInOutBuffers.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestSessionInOutBuffers.jav0100644 0000000 0000000 00000061473 12613456013 032440 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.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.MessageConstraintException; 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(Consts.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(Consts.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(Consts.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 looooooooooooooooooooooooooooooooooooooooooong line\r\n"; final byte[] tmp = s.getBytes(Consts.ASCII); // no limit final SessionInputBufferMock inbuffer1 = new SessionInputBufferMock(tmp, 5, MessageConstraints.DEFAULT); Assert.assertNotNull(inbuffer1.readLine()); final 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("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } } @Test public void testLineLimit2() throws Exception { final String s = "just a line\r\n"; final byte[] tmp = s.getBytes(Consts.ASCII); // no limit final SessionInputBufferMock inbuffer1 = new SessionInputBufferMock(tmp, 25, MessageConstraints.DEFAULT); Assert.assertNotNull(inbuffer1.readLine()); final long bytesRead = inbuffer1.getMetrics().getBytesTransferred(); Assert.assertEquals(13, bytesRead); // 10 char limit final SessionInputBufferMock inbuffer2 = new SessionInputBufferMock(tmp, 25, MessageConstraints.lineLen(10)); try { inbuffer2.readLine(); Assert.fail("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } } @Test public void testReadLineFringeCase1() throws Exception { final String s = "abc\r\n"; final byte[] tmp = s.getBytes(Consts.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(Consts.UTF_8).length + 2)+ (s2.getBytes(Consts.UTF_8).length + 2) + (s3.getBytes(Consts.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).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); 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); 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); 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.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestMessageParser.java0100644 0000000 0000000 00000017410 12613456013 031413 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460515 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestContentLengthInputStream.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestContentLengthInputStrea0100644 0000000 0000000 00000014137 12613456013 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.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.ConnectionClosedException; import org.apache.http.Consts; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.io.SessionInputBuffer; import org.junit.Assert; import org.junit.Test; public class TestContentLengthInputStream { @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(correct, Consts.ISO_8859_1), 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 = new String(out.toByteArray(), Consts.ISO_8859_1); 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(correct, Consts.ISO_8859_1); 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(correct, Consts.ISO_8859_1); 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) { } } } ././@LongLink0100644 0000000 0000000 00000000146 12613460515 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestIdentityInputStream.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestIdentityInputStream.jav0100644 0000000 0000000 00000007333 12613456013 032501 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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(); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestRequestParser.java0100644 0000000 0000000 00000011076 12613456013 031461 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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(Consts.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); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestResponseParser.java0100644 0000000 0000000 00000011201 12613456013 031615 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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(Consts.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); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460515 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestIdentityOutputStream.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestIdentityOutputStream.ja0100644 0000000 0000000 00000011623 12613456013 032511 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 } } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/io/TestChunkCoding.java0100644 0000000 0000000 00000044707 12613456013 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.ConnectionClosedException; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.MalformedChunkCodingException; import org.apache.http.MessageConstraintException; import org.apache.http.TruncatedChunkException; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.SessionInputBufferMock; import org.apache.http.impl.SessionOutputBufferMock; import org.apache.http.io.SessionInputBuffer; import org.junit.Assert; import org.junit.Test; public class TestChunkCoding { @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(CHUNKED_INPUT, Consts.ISO_8859_1)); 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 = new String(out.toByteArray(), Consts.ISO_8859_1); 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(CHUNKED_INPUT, Consts.ISO_8859_1)); 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(); 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(s, Consts.ISO_8859_1)); 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(s, Consts.ISO_8859_1)); 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(s, Consts.ISO_8859_1)); 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(expected=ConnectionClosedException.class) public void testChunkedInputStreamNoClosingChunk() throws IOException { final String s = "5\r\n01234\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); final byte[] tmp = new byte[5]; Assert.assertEquals(5, in.read(tmp)); in.read(); in.close(); } // Truncated stream (missing closing CRLF) @Test(expected=MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamTruncatedCRLF() throws IOException { final String s = "5\r\n01234"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); final byte[] tmp = new byte[5]; Assert.assertEquals(5, in.read(tmp)); in.read(); in.close(); } // Missing \r\n at the end of the first chunk @Test(expected=MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamMissingCRLF() throws IOException { final String s = "5\r\n012345\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); final byte[] buffer = new byte[300]; final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); } // Missing LF @Test(expected=MalformedChunkCodingException.class) 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(s, Consts.ISO_8859_1)); in.read(); in.close(); } // Invalid chunk size @Test(expected = MalformedChunkCodingException.class) 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(s, Consts.ISO_8859_1)); in.read(); in.close(); } // Negative chunk size @Test(expected = MalformedChunkCodingException.class) 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(s, Consts.ISO_8859_1)); in.read(); in.close(); } // Truncated chunk @Test(expected = TruncatedChunkException.class) public void testCorruptChunkedInputStreamTruncatedChunk() throws IOException { final String s = "3\r\n12"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); final byte[] buffer = new byte[300]; Assert.assertEquals(2, in.read(buffer)); in.read(buffer); in.close(); } // Invalid footer @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamInvalidFooter() throws IOException { final String s = "1\r\n0\r\n0\r\nstuff\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); in.read(); in.read(); in.close(); } @Test public void testCorruptChunkedInputStreamClose() throws IOException { final String s = "whatever\r\n01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); try { in.read(); Assert.fail("MalformedChunkCodingException expected"); } catch (MalformedChunkCodingException ex) { } in.close(); } @Test public void testEmptyChunkedInputStream() throws IOException { final String input = "0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(input, Consts.ISO_8859_1)); 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 testTooLongChunkHeader() throws IOException { final String input = "5; and some very looooong commend\r\n12345\r\n0\r\n"; final InputStream in1 = new ChunkedInputStream( new SessionInputBufferMock(input, MessageConstraints.DEFAULT, Consts.ISO_8859_1)); final byte[] buffer = new byte[300]; Assert.assertEquals(5, in1.read(buffer)); in1.close(); final InputStream in2 = new ChunkedInputStream( new SessionInputBufferMock(input, MessageConstraints.lineLen(10), Consts.ISO_8859_1)); try { in2.read(buffer); Assert.fail("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } finally { try { in2.close(); } catch (MessageConstraintException ex) { } } } @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(input.getBytes(Consts.ISO_8859_1)); 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 = new String(result.toByteArray(), Consts.ISO_8859_1); 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(Consts.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(Consts.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.4.4/httpcore/src/test/java/org/apache/http/impl/entity/0040755 0000000 0000000 00000000000 12613456014 026055 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000174 12613460515 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/entity/TestDisallowIdentityContentLengthStrategy.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/entity/TestDisallowIdentityCon0100644 0000000 0000000 00000004640 12613456014 032571 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } } ././@LongLink0100644 0000000 0000000 00000000162 12613460515 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/entity/TestStrictContentLengthStrategy.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/entity/TestStrictContentLength0100644 0000000 0000000 00000010574 12613456014 032611 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460515 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/entity/TestLaxContentLengthStrategy.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/entity/TestLaxContentLengthStr0100644 0000000 0000000 00000014100 12613456014 032543 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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)); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/impl/entity/DummyHttpMessage.java0100644 0000000 0000000 00000003334 12613456014 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.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); } @Override public ProtocolVersion getProtocolVersion() { return ver; } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/entity/0040755 0000000 0000000 00000000000 12613456015 025115 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/entity/TestByteArrayEntity.java0100644 0000000 0000000 00000012566 12613456015 031726 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); 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); 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); new ByteArrayEntity(bytes, 0, bytes.length + 1); } @Test(expected=IndexOutOfBoundsException.class) public void testIllegalConstructorBadOff1() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII); new ByteArrayEntity(bytes, -1, bytes.length); } @Test(expected=IndexOutOfBoundsException.class) public void testIllegalConstructorBadOff2() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII); new ByteArrayEntity(bytes, bytes.length + 1, bytes.length); } @Test public void testWriteTo() throws Exception { final byte[] bytes = "Message content".getBytes(Consts.ASCII); 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); 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.4.4/httpcore/src/test/java/org/apache/http/entity/TestInputStreamEntity.java0100644 0000000 0000000 00000012024 12613456015 032264 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); 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); 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); 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); 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.4.4/httpcore/src/test/java/org/apache/http/entity/TestBasicHttpEntity.java0100644 0000000 0000000 00000007722 12613456015 031703 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); 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); 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); 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.4.4/httpcore/src/test/java/org/apache/http/entity/TestSerializableEntity.java0100644 0000000 0000000 00000012210 12613456015 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.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.4.4/httpcore/src/test/java/org/apache/http/entity/TestStringEntity.java0100644 0000000 0000000 00000013104 12613456015 031257 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); 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); 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.4.4/httpcore/src/test/java/org/apache/http/entity/TestFileEntity.java0100644 0000000 0000000 00000006771 12613456015 030704 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/entity/TestBufferedHttpEntity.java0100644 0000000 0000000 00000012776 12613456015 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.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); 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); 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); 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); 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.4.4/httpcore/src/test/java/org/apache/http/entity/TestEntityTemplate.java0100644 0000000 0000000 00000007061 12613456015 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.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() { @Override 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() { @Override 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() { @Override 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.4.4/httpcore/src/test/java/org/apache/http/entity/TestContentType.java0100644 0000000 0000000 00000025110 12613456015 031070 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 java.nio.charset.UnsupportedCharsetException; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.ParseException; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; 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(Consts.ASCII, contentType.getCharset()); 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(Consts.ASCII, contentType.getCharset()); 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(Consts.ASCII, contentType.getCharset()); Assert.assertEquals("text/plain; charset=US-ASCII", contentType.toString()); contentType = contentType.withCharset("UTF-8"); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals(Consts.UTF_8, contentType.getCharset()); 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(Consts.ASCII, contentType.getCharset()); } @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(Consts.ASCII, contentType.getCharset()); 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(Consts.ASCII, contentType.getCharset()); 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(Consts.UTF_8, contentType.getCharset()); } @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()); } @Test(expected = UnsupportedCharsetException.class) public void testExtractInvalidCharset() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContentType(new BasicHeader("Content-Type", "text/plain; charset = stuff")); ContentType.get(httpentity); } @Test public void testExtracLenienttNullInput() throws Exception { Assert.assertNull(ContentType.getLenient(null)); } @Test public void testExtractLenientNullContentType() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContentType((Header) null); Assert.assertNull(ContentType.getLenient(httpentity)); } @Test public void testLenientExtractInvalidCharset() throws Exception { final BasicHttpEntity httpentity = new BasicHttpEntity(); httpentity.setContentType(new BasicHeader("Content-Type", "text/plain; charset = stuff")); final ContentType contentType = ContentType.getLenient(httpentity); Assert.assertNotNull(contentType); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals(null, contentType.getCharset()); } @Test public void testWithParams() throws Exception { ContentType contentType = ContentType.create("text/plain", new BasicNameValuePair("charset", "UTF-8"), new BasicNameValuePair("p", "this"), new BasicNameValuePair("p", "that")); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals(Consts.UTF_8, contentType.getCharset()); Assert.assertEquals("text/plain; charset=UTF-8; p=this; p=that", contentType.toString()); contentType = contentType.withParameters( new BasicNameValuePair("charset", "ascii"), new BasicNameValuePair("p", "this and that")); Assert.assertEquals("text/plain", contentType.getMimeType()); Assert.assertEquals(Consts.ASCII, contentType.getCharset()); Assert.assertEquals("text/plain; charset=ascii; p=\"this and that\"", contentType.toString()); contentType = ContentType.create("text/blah").withParameters( new BasicNameValuePair("p", "blah")); Assert.assertEquals("text/blah", contentType.getMimeType()); Assert.assertEquals(null, contentType.getCharset()); Assert.assertEquals("text/blah; p=blah", contentType.toString()); contentType = ContentType.create("text/blah", Consts.ISO_8859_1).withParameters( new BasicNameValuePair("p", "blah")); Assert.assertEquals("text/blah", contentType.getMimeType()); Assert.assertEquals(Consts.ISO_8859_1, contentType.getCharset()); Assert.assertEquals("text/blah; charset=ISO-8859-1; p=blah", contentType.toString()); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/entity/TestHttpEntityWrapper.java0100644 0000000 0000000 00000010163 12613456015 032273 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); 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.4.4/httpcore/src/test/java/org/apache/http/entity/TestAbstractHttpEntity.java0100644 0000000 0000000 00000006517 12613456015 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.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.4.4/httpcore/src/test/java/org/apache/http/integration/0040755 0000000 0000000 00000000000 12613456014 026123 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/integration/TestSyncHttp.java0100644 0000000 0000000 00000110721 12613456014 031401 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.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() { @Override 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() { @Override 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() { @Override 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() { @Override 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() { @Override 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() { @Override 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() { @Override 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; b = content.getBytes(cs); this.raw = b; this.n = n; } @Override public InputStream getContent() throws IOException, IllegalStateException { throw new IllegalStateException("This method is not implemented"); } @Override public long getContentLength() { return (this.raw.length + 2) * this.n; } @Override public boolean isRepeatable() { return true; } @Override public boolean isStreaming() { return false; } @Override 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() { @Override 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() { @Override 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() { @Override 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() { @Override 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() { @Override 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() { @Override 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.4.4/httpcore/src/test/java/org/apache/http/testserver/0040755 0000000 0000000 00000000000 12613456015 026007 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/testserver/HttpClient.java0100644 0000000 0000000 00000010377 12613456015 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.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.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 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); } } httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/testserver/HttpServer.java0100644 0000000 0000000 00000012035 12613456015 030756 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.InetAddress; import java.net.Socket; import java.net.SocketException; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.ConnectionClosedException; import org.apache.http.ExceptionLogger; import org.apache.http.HttpConnectionFactory; import org.apache.http.config.SocketConfig; import org.apache.http.impl.bootstrap.ServerBootstrap; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.UriHttpRequestHandlerMapper; import org.apache.http.util.Asserts; public class HttpServer { private final UriHttpRequestHandlerMapper reqistry; private volatile HttpExpectationVerifier expectationVerifier; private volatile int timeout; private volatile org.apache.http.impl.bootstrap.HttpServer server; public HttpServer() throws IOException { super(); this.reqistry = new UriHttpRequestHandlerMapper(); } 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; } public int getPort() { final org.apache.http.impl.bootstrap.HttpServer local = this.server; if (local != null) { return this.server.getLocalPort(); } else { throw new IllegalStateException("Server not running"); } } public InetAddress getInetAddress() { final org.apache.http.impl.bootstrap.HttpServer local = this.server; if (local != null) { return local.getInetAddress(); } else { throw new IllegalStateException("Server not running"); } } public void start() throws IOException { Asserts.check(this.server == null, "Server already running"); this.server = ServerBootstrap.bootstrap() .setSocketConfig(SocketConfig.custom() .setSoTimeout(this.timeout) .build()) .setServerInfo("TEST-SERVER/1.1") .setConnectionFactory(new LoggingConnFactory()) .setExceptionLogger(new SimpleExceptionLogger()) .setExpectationVerifier(this.expectationVerifier) .setHandlerMapper(this.reqistry) .create(); this.server.start(); } public void shutdown() { final org.apache.http.impl.bootstrap.HttpServer local = this.server; this.server = null; if (local != null) { local.shutdown(5, TimeUnit.SECONDS); } } static class LoggingConnFactory implements HttpConnectionFactory { @Override public LoggingBHttpServerConnection createConnection(final Socket socket) throws IOException { final LoggingBHttpServerConnection conn = new LoggingBHttpServerConnection(8 * 1024); conn.bind(socket); return conn; } } static class SimpleExceptionLogger implements ExceptionLogger { private final Log log = LogFactory.getLog(HttpServer.class); @Override public void log(final Exception ex) { if (ex instanceof ConnectionClosedException) { this.log.debug(ex.getMessage()); } else if (ex instanceof SocketException) { this.log.debug(ex.getMessage()); } else { this.log.error(ex.getMessage(), ex); } } } } ././@LongLink0100644 0000000 0000000 00000000156 12613460515 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/testserver/LoggingBHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/testserver/LoggingBHttpClientConnec0100644 0000000 0000000 00000012210 12613456015 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.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 12613460515 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/testserver/LoggingOutputStream.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/testserver/LoggingOutputStream.java0100644 0000000 0000000 00000004113 12613456015 032631 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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(); } } ././@LongLink0100644 0000000 0000000 00000000156 12613460515 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/testserver/LoggingBHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore/src/test/java/org/apache/http/testserver/LoggingBHttpServerConnec0100644 0000000 0000000 00000012215 12613456015 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.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.4.4/httpcore/src/test/java/org/apache/http/testserver/Wire.java0100644 0000000 0000000 00000006121 12613456015 027555 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/test/java/org/apache/http/testserver/LoggingInputStream.java0100644 0000000 0000000 00000005351 12613456015 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.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.4.4/httpcore/src/test/resources/0040755 0000000 0000000 00000000000 12613456016 021704 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/resources/CA/0040755 0000000 0000000 00000000000 12613456015 022166 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/test/resources/CA/openssl.cnf0100644 0000000 0000000 00000026072 12613456015 024345 0ustar000000000 0000000 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # # This definition stops the following lines choking if HOME isn't # defined. HOME = . RANDFILE = $ENV::HOME/.rnd # Extra OBJECT IDENTIFIER info: #oid_file = $ENV::HOME/.oid oid_section = new_oids # To use this configuration file with the "-extfile" option of the # "openssl x509" utility, name here the section containing the # X.509v3 extensions to use: # extensions = # (Alternatively, use a configuration file that has only # X.509v3 extensions in its main [= default] section.) [ new_oids ] # We can add new OIDs in here for use by 'ca', 'req' and 'ts'. # Add a simple OID like this: # testoid1=1.2.3.4 # Or use config file substitution like this: # testoid2=${testoid1}.5.6 # Policies used by the TSA examples. tsa_policy1 = 1.2.3.4.1 tsa_policy2 = 1.2.3.4.5.6 tsa_policy3 = 1.2.3.4.5.7 #################################################################### [ ca ] default_ca = CA_default # The default ca section #################################################################### [ CA_default ] dir = ./demoCA # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file. #unique_subject = no # Set to 'no' to allow creation of # several ctificates with same subject. new_certs_dir = $dir/newcerts # default place for new certs. certificate = $dir/cacert.pem # The CA certificate serial = $dir/serial # The current serial number crlnumber = $dir/crlnumber # the current crl number # must be commented out to leave a V1 CRL crl = $dir/crl.pem # The current CRL private_key = $dir/private/cakey.pem# The private key RANDFILE = $dir/private/.rand # private random number file x509_extensions = usr_cert # The extentions to add to the cert # Comment out the following two lines for the "traditional" # (and highly broken) format. name_opt = ca_default # Subject Name options cert_opt = ca_default # Certificate field options # Extension copying option: use with caution. # copy_extensions = copy # Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs # so this is commented out by default to leave a V1 CRL. # crlnumber must also be commented out to leave a V1 CRL. # crl_extensions = crl_ext default_days = 365 # how long to certify for default_crl_days= 30 # how long before next CRL default_md = default # use public key default MD preserve = no # keep passed DN ordering # A few difference way of specifying how similar the request should look # For type CA, the listed attributes must be the same, and the optional # and supplied fields are just that :-) policy = policy_match # For the CA policy [ policy_match ] countryName = match stateOrProvinceName = match organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional # For the 'anything' policy # At this point in time, you must list all acceptable 'object' # types. [ policy_anything ] countryName = optional stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional #################################################################### [ req ] default_bits = 2048 default_keyfile = privkey.pem distinguished_name = req_distinguished_name attributes = req_attributes x509_extensions = v3_ca # The extentions to add to the self signed cert # Passwords for private keys if not present they will be prompted for # input_password = secret # output_password = secret # This sets a mask for permitted string types. There are several options. # default: PrintableString, T61String, BMPString. # pkix : PrintableString, BMPString (PKIX recommendation before 2004) # utf8only: only UTF8Strings (PKIX recommendation after 2004). # nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings). # MASK:XXXX a literal mask value. # WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings. string_mask = utf8only # req_extensions = v3_req # The extensions to add to a certificate request [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = Some-State localityName = Locality Name (eg, city) 0.organizationName = Organization Name (eg, company) 0.organizationName_default = Apache Software Foundation organizationalUnitName = Organizational Unit Name (eg, section) organizationalUnitName_default = HttpComponents Project commonName = Common Name (e.g. server FQDN or YOUR name) commonName_max = 64 emailAddress = Email Address emailAddress_max = 64 # SET-ex3 = SET extension number 3 [ req_attributes ] challengePassword = A challenge password challengePassword_min = 4 challengePassword_max = 20 unstructuredName = An optional company name [ usr_cert ] # These extensions are added when 'ca' signs a request. # This goes against PKIX guidelines but some CAs do it and some software # requires this to avoid interpreting an end user certificate as a CA. basicConstraints=CA:FALSE # Here are some examples of the usage of nsCertType. If it is omitted # the certificate can be used for anything *except* object signing. # This is OK for an SSL server. # nsCertType = server # For an object signing certificate this would be used. # nsCertType = objsign # For normal client use this is typical # nsCertType = client, email # and for everything including object signing: # nsCertType = client, email, objsign # This is typical in keyUsage for a client certificate. # keyUsage = nonRepudiation, digitalSignature, keyEncipherment # This will be displayed in Netscape's comment listbox. nsComment = "OpenSSL Generated Certificate" # PKIX recommendations harmless if included in all certificates. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer # This stuff is for subjectAltName and issuerAltname. # Import the email address. # subjectAltName=email:copy # An alternative to produce certificates that aren't # deprecated according to PKIX. # subjectAltName=email:move # Copy subject details # issuerAltName=issuer:copy #nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem #nsBaseUrl #nsRevocationUrl #nsRenewalUrl #nsCaPolicyUrl #nsSslServerName # This is required for TSA certificates. # extendedKeyUsage = critical,timeStamping [ v3_req ] # Extensions to add to a certificate request basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment [ v3_ca ] # Extensions for a typical CA # PKIX recommendation. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer # This is what PKIX recommends but some broken software chokes on critical # extensions. #basicConstraints = critical,CA:true # So we do this instead. basicConstraints = CA:true # Key usage: this is typical for a CA certificate. However since it will # prevent it being used as an test self-signed certificate it is best # left out by default. # keyUsage = cRLSign, keyCertSign # Some might want this also # nsCertType = sslCA, emailCA # Include email address in subject alt name: another PKIX recommendation # subjectAltName=email:copy # Copy issuer details # issuerAltName=issuer:copy # DER hex encoding of an extension: beware experts only! # obj=DER:02:03 # Where 'obj' is a standard or added object # You can even override a supported extension: # basicConstraints= critical, DER:30:03:01:01:FF [ crl_ext ] # CRL extensions. # Only issuerAltName and authorityKeyIdentifier make any sense in a CRL. # issuerAltName=issuer:copy authorityKeyIdentifier=keyid:always [ proxy_cert_ext ] # These extensions should be added when creating a proxy certificate # This goes against PKIX guidelines but some CAs do it and some software # requires this to avoid interpreting an end user certificate as a CA. basicConstraints=CA:FALSE # Here are some examples of the usage of nsCertType. If it is omitted # the certificate can be used for anything *except* object signing. # This is OK for an SSL server. # nsCertType = server # For an object signing certificate this would be used. # nsCertType = objsign # For normal client use this is typical # nsCertType = client, email # and for everything including object signing: # nsCertType = client, email, objsign # This is typical in keyUsage for a client certificate. # keyUsage = nonRepudiation, digitalSignature, keyEncipherment # This will be displayed in Netscape's comment listbox. nsComment = "OpenSSL Generated Certificate" # PKIX recommendations harmless if included in all certificates. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer # This stuff is for subjectAltName and issuerAltname. # Import the email address. # subjectAltName=email:copy # An alternative to produce certificates that aren't # deprecated according to PKIX. # subjectAltName=email:move # Copy subject details # issuerAltName=issuer:copy #nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem #nsBaseUrl #nsRevocationUrl #nsRenewalUrl #nsCaPolicyUrl #nsSslServerName # This really needs to be in place for it to be a proxy certificate. proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo #################################################################### [ tsa ] default_tsa = tsa_config1 # the default TSA section [ tsa_config1 ] # These are used by the TSA reply generation only. dir = ./demoCA # TSA root directory serial = $dir/tsaserial # The current serial number (mandatory) crypto_device = builtin # OpenSSL engine to use for signing signer_cert = $dir/tsacert.pem # The TSA signing certificate # (optional) certs = $dir/cacert.pem # Certificate chain to include in reply # (optional) signer_key = $dir/private/tsakey.pem # The TSA private key (optional) default_policy = tsa_policy1 # Policy if request did not specify it # (optional) other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional) digests = md5, sha1 # Acceptable message digests (mandatory) accuracy = secs:1, millisecs:500, microsecs:100 # (optional) clock_precision_digits = 0 # number of digits after dot. (optional) ordering = yes # Is ordering defined for timestamps? # (optional, default: no) tsa_name = yes # Must the TSA name be included in the reply? # (optional, default: no) ess_cert_id_chain = no # Must the ESS cert id chain be included? # (optional, default: no) httpcomponents-core-4.4.4/httpcore/src/test/resources/CA/ca-key.pem0100644 0000000 0000000 00000003452 12613456015 024043 0ustar000000000 0000000 -----BEGIN ENCRYPTED PRIVATE KEY----- MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIq0bLh96mWv4CAggA MBQGCCqGSIb3DQMHBAimZqUiELx13QSCBMgaLWrGFqveIzwQUsebS6FBdVq0lodz Vlekje8ycFDYSd21V9jPMwrSupZceeBQjCrpyLZ3oPkR+MvObmznev8XYcJzVCkF E9ApAaHZe248wWcu1/D7auHNG3GyZfvYS0c//Rs2OzMZfsUvX93RVullCRREvCYS qXhaO3ywFocndKRpSnkOBs2SRa0yc9POl4n4dwyKhsJUaMSmhPbJr9UBvCbXHZIA gLcSWzVon3EtZCSubMp9eo90G5MzIXEyPBTcIHwpyqRWTkaTUTq4R0c4/RTX+l7K OZuRIEeBEW6z009fSagymN/KEH3gUkg5pG6i1YWF63OVKTMGn+yQGWwYXwTyEGi5 HZpD98wh3ycucmL93XLk+yYXQcTp1i+u4GaXNWGREQvNW6onCGeg6WWj1PrIsqoi TZ2pgQUJWPR1K3037hY0o9sakAkyYSyTPVvHOUcbf3+GhqGS1FsSNOxKRNpYm/3v Gf0SUN8BavPliK9NSU5JAbprr/hoL5o72dCX9DiOgwfW3HyD/gLh7sVyVBdAzTnE XFaYFnrb5QnqHbgWvaLbJUT5K7MW3OFLVConydYtYdaUl5z49OflhgnvYOPgTSUr k9c7exQjedAduPd8dXODh9l2g+QEXJoT+YYFEYHkQlsZgH1hCLXD1TmAeI4LMklb vPaGE8Ouj1pfbejdTNsqLfW0IiR/jZzEjRgqrueMf2VUjtqTZyPayc2rU4kOoKhv JzQ0wOFhgRztWJy2voRe+iYss3ToqZ7qLpjBfCTsxCJqbuaGeJWWSnOlDpSysgr+ q4BvCzDcvf/0mKD2cQuJx/kynQMCcWB/VegRsQ24Y+3T7IU1w8ccmRfSZ93AwkAh MKJzKaVhD/gn9vUG/we18p7RMIc9pk1o2Z2Ru3mKjkO3QYRP6Y7yk0ah2JKrHIPf LWfPuHmtzHQXkY3RbVvxvwD/+qHm8ogXq52w8cpGhY5UwAEHrLLwypdBHccrAJjo bE13M/MrtTry/k8OMRqhhRzHUXBq6mLaWffCaP2SAVfJEez2iASvGJFvgy3bSkWY rwWMSfZKDkauwDMW5gpFrpeuqgD64LO72sN01riVDpaEyNODRCEEBGce+O+91R9K TLVgRYFsxClyZy1nynD66gkTepEm1yOgcdqV3651Os+TGm39jGYHy1k9mPz8ypqf 8n8uw4nV3SbIwfpy4Z8onHixfc/Fugm7yQHW4dSuCpahyIJHom6Cq7SZfPuo9e3t 8tqaxvK4U/dAXoimvN1eakH2FoVFIj3mk7OAKBgmDINH9GlzXPwRsTfiJSP4Xaod ouWIQLLeXQuuOc5VJd1Xex75o8ciSOomAS0uR4Fvk/2NkAm0EMddjZnuWLQaXPry JiUIgSx3w3yRq9RSQOxDRQpp2nP2roX7cyeGPzTmeujikExGTa3YBxuAShDLx5pt fpi0ol8H8ohDU4eV9pv96KRBG9e8sQf1zpGjeYLTFiN35IQxYJx3HTXp9/oFWkmA OdCEwggIKJ/RtgkWOWogTilQVA41p4XZr661fxoSE86sHXkZKn8IGnAKLFT46nWM IYVDalYUiSNZr+KbzmLIV3LmYE3mlqGI4vDvQtd9zQk/uatYBc2DetuTWPZHCEKS 3Nk= -----END ENCRYPTED PRIVATE KEY----- httpcomponents-core-4.4.4/httpcore/src/test/resources/CA/ca-cert.pem0100644 0000000 0000000 00000002537 12613456015 024213 0ustar000000000 0000000 -----BEGIN CERTIFICATE----- MIIDyTCCArGgAwIBAgIJAO3mCIu9mboMMA0GCSqGSIb3DQEBCwUAMHoxIzAhBgNV BAoMGkFwYWNoZSBTb2Z0d2FyZSBGb3VuZGF0aW9uMR8wHQYDVQQLDBZIdHRwQ29t cG9uZW50cyBQcm9qZWN0MRAwDgYDVQQDDAdUZXN0IENBMSAwHgYJKoZIhvcNAQkB FhFkZXZAaGMuYXBhY2hlLm9yZzAgFw0xNDEwMTMxNTAxMjBaGA8yMjg4MDcyODE1 MDEyMFowejEjMCEGA1UECgwaQXBhY2hlIFNvZnR3YXJlIEZvdW5kYXRpb24xHzAd BgNVBAsMFkh0dHBDb21wb25lbnRzIFByb2plY3QxEDAOBgNVBAMMB1Rlc3QgQ0Ex IDAeBgkqhkiG9w0BCQEWEWRldkBoYy5hcGFjaGUub3JnMIIBIjANBgkqhkiG9w0B AQEFAAOCAQ8AMIIBCgKCAQEApXhHtKRvAxbLI+f21zNe68dkVXAhSMIfHQJGb2en S1H8yE4HPIb4vPQ0U7fQCb7RXplm6cHExpof4cO3DmyqD5KeQk0TdM8XrhviDgwj Y0KQ/lgwGHR5CpYoZ6LYWaLSE/wt9dVu80UcK8a3hW9G0X/4b79fMO6HYDix+CI4 b17sqZ4K0tWKA10Xe+2RJU8Y01pPBaPR/UsAn+a1pZ6f8BhL879oWHfLWKcgZOYP U4sYED0S8gs4/ED1zRj2/uHb313sHTl+OU4X5v+OvwBvbNBrl5qfMTZnRNxlOfRq UTJdcopsp2aNeqHiorSDOrHwMIJpxQ2XqHT2l9s8msXf4wIDAQABo1AwTjAdBgNV HQ4EFgQUA+Tn2g9k2xMevYWrdrwpyi+nx0swHwYDVR0jBBgwFoAUA+Tn2g9k2xMe vYWrdrwpyi+nx0swDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAFVEp 8Nv6JoFY7oGgu6068fH/kq7A3SllqMpbv7dddI9fgwy352cBtg6PkYkGtEE037xs FQSYV1NiAkNWTJER+Q+kVbQrhuPNKZqh1g0sUKwv3X20BmgJ9hbU9klWZjdjujyd h9Ybjuntkn5XPp1zN6zHD0sQReEJnRlD6FT1axrQWpICzE4qoo8k64G+6/rqFywc oMc/Of3KCAHjtbWklEu97hjBvGC/nEP4/VhRrjWWSeGHv88LCyO/Yg6v3zrZHFLW +KhsDCPyLxSSISFskLQfukiqf2lr87kQq/oF27sAr3sR3Jqh4qzflM2XLgjmZuRE OrHT6lvUemRyksA5qg== -----END CERTIFICATE----- httpcomponents-core-4.4.4/httpcore/src/main/0040755 0000000 0000000 00000000000 12613456022 017634 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/0040755 0000000 0000000 00000000000 12613456016 020560 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/0040755 0000000 0000000 00000000000 12613456016 021347 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/0040755 0000000 0000000 00000000000 12613456016 022570 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/0040755 0000000 0000000 00000000000 12613456022 023544 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ParseException.java0100644 0000000 0000000 00000004047 12613456021 027341 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} */ public ParseException(final String message) { super(message); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ExceptionLogger.java0100644 0000000 0000000 00000003157 12613456022 027510 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; /** * @since 4.4 */ public interface ExceptionLogger { public static final ExceptionLogger NO_OP = new ExceptionLogger() { @Override public void log(final Exception ex) { } }; public static final ExceptionLogger STD_ERR = new ExceptionLogger() { @Override public void log(final Exception ex) { ex.printStackTrace(); } }; void log(Exception ex); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HttpHost.java0100644 0000000 0000000 00000024430 12613456021 026163 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code HttpHost} instance with the given scheme, hostname and port. * * @param hostname the hostname (IP or DNS name) * @param port the port number. * {@code -1} indicates the scheme default port. * @param scheme the name of the scheme. * {@code null} indicates the * {@link #DEFAULT_SCHEME_NAME default scheme} */ public HttpHost(final String hostname, final int port, final String scheme) { super(); this.hostname = Args.containsNoBlanks(hostname, "Host name"); this.lcHostname = hostname.toLowerCase(Locale.ROOT); if (scheme != null) { this.schemeName = scheme.toLowerCase(Locale.ROOT); } else { this.schemeName = DEFAULT_SCHEME_NAME; } this.port = port; this.address = null; } /** * Creates {@code HttpHost} instance with the default scheme and the given hostname and port. * * @param hostname the hostname (IP or DNS name) * @param port the port number. * {@code -1} indicates the scheme default port. */ public HttpHost(final String hostname, final int port) { this(hostname, port, null); } /** * Creates {@code HttpHost} instance from string. Text may not contain any blanks. * * @since 4.4 */ public static HttpHost create(final String s) { Args.containsNoBlanks(s, "HTTP Host"); String text = s; String scheme = null; final int schemeIdx = text.indexOf("://"); if (schemeIdx > 0) { scheme = text.substring(0, schemeIdx); text = text.substring(schemeIdx + 3); } int port = -1; final int portIdx = text.lastIndexOf(":"); if (portIdx > 0) { try { port = Integer.parseInt(text.substring(portIdx + 1)); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Invalid HTTP host: " + text); } text = text.substring(0, portIdx); } return new HttpHost(text, port, scheme); } /** * Creates {@code HttpHost} instance with the default scheme and port and the given hostname. * * @param hostname the hostname (IP or DNS name) */ public HttpHost(final String hostname) { this(hostname, -1, null); } /** * Creates {@code HttpHost} instance with the given scheme, inet address and port. * * @param address the inet address. * @param port the port number. * {@code -1} indicates the scheme default port. * @param scheme the name of the scheme. * {@code null} indicates the * {@link #DEFAULT_SCHEME_NAME default scheme} * * @since 4.3 */ public HttpHost(final InetAddress address, final int port, final String scheme) { this(Args.notNull(address,"Inet address"), address.getHostName(), port, scheme); } /** * Creates a new {@link HttpHost HttpHost}, specifying all values. * Constructor for HttpHost. * * @param address the inet address. * @param hostname the hostname (IP or DNS name) * @param port the port number. * {@code -1} indicates the scheme default port. * @param scheme the name of the scheme. * {@code null} indicates the * {@link #DEFAULT_SCHEME_NAME default scheme} * * @since 4.4 */ public HttpHost(final InetAddress address, final String hostname, final int port, final String scheme) { super(); this.address = Args.notNull(address, "Inet address"); this.hostname = Args.notNull(hostname, "Hostname"); this.lcHostname = this.hostname.toLowerCase(Locale.ROOT); if (scheme != null) { this.schemeName = scheme.toLowerCase(Locale.ROOT); } else { this.schemeName = DEFAULT_SCHEME_NAME; } this.port = port; } /** * Creates {@code HttpHost} instance with the default scheme and the given inet address * and port. * * @param address the inet address. * @param port the port number. * {@code -1} indicates the scheme default port. * * @since 4.3 */ public HttpHost(final InetAddress address, final int port) { this(address, port, null); } /** * Creates {@code HttpHost} instance with the default scheme and port and the given inet * address. * * @param address the inet address. * * @since 4.3 */ public HttpHost(final InetAddress address) { this(address, -1, null); } /** * Copy constructor for {@link HttpHost HttpHost}. * * @param httphost the HTTP host to copy details from */ public HttpHost (final HttpHost httphost) { super(); Args.notNull(httphost, "HTTP host"); this.hostname = httphost.hostname; this.lcHostname = httphost.lcHostname; this.schemeName = httphost.schemeName; this.port = httphost.port; this.address = httphost.address; } /** * Returns the host name. * * @return the host name (IP or DNS name) */ public String getHostName() { return this.hostname; } /** * Returns the port. * * @return the host port, or {@code -1} if not set */ public int getPort() { return this.port; } /** * Returns the scheme name. * * @return the scheme name */ public String getSchemeName() { return this.schemeName; } /** * Returns the inet address if explicitly set by a constructor, * {@code null} otherwise. * @return the inet address * * @since 4.3 */ public InetAddress getAddress() { return this.address; } /** * Return the host URI, as a string. * * @return the host URI */ public String toURI() { final StringBuilder buffer = new StringBuilder(); buffer.append(this.schemeName); buffer.append("://"); buffer.append(this.hostname); if (this.port != -1) { buffer.append(':'); buffer.append(Integer.toString(this.port)); } return buffer.toString(); } /** * Obtains the host string, without scheme prefix. * * @return the host string, for example {@code localhost:8080} */ public String toHostString() { if (this.port != -1) { //the highest port number is 65535, which is length 6 with the addition of the colon final StringBuilder buffer = new StringBuilder(this.hostname.length() + 6); buffer.append(this.hostname); buffer.append(":"); buffer.append(Integer.toString(this.port)); return buffer.toString(); } else { return this.hostname; } } @Override public String toString() { return toURI(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof HttpHost) { final HttpHost that = (HttpHost) obj; return this.lcHostname.equals(that.lcHostname) && this.port == that.port && this.schemeName.equals(that.schemeName) && (this.address==null ? that.address== null : this.address.equals(that.address)); } else { return false; } } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.lcHostname); hash = LangUtils.hashCode(hash, this.port); hash = LangUtils.hashCode(hash, this.schemeName); if (address!=null) { hash = LangUtils.hashCode(hash, address); } return hash; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HttpRequest.java0100644 0000000 0000000 00000003544 12613456021 026701 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/TokenIterator.java0100644 0000000 0000000 00000003706 12613456022 027204 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code true} if there is another token, * {@code false} otherwise */ @Override boolean hasNext(); /** * Obtains the next token from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next token in this iteration */ String nextToken(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HttpInetConnection.java0100644 0000000 0000000 00000002745 12613456021 030172 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpServerConnection.java0100644 0000000 0000000 00000006272 12613456022 030541 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpResponse.java0100644 0000000 0000000 00000011713 12613456022 027045 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} if not yet set */ StatusLine getStatusLine(); /** * Sets the status line of this response. * * @param statusline the status line of this response */ void setStatusLine(StatusLine statusline); /** * Sets the status line of this response. * The reason phrase will be determined based on the current * {@link #getLocale locale}. * * @param ver the HTTP version * @param code the status code */ void setStatusLine(ProtocolVersion ver, int code); /** * Sets the status line of this response with a reason phrase. * * @param ver the HTTP version * @param code the status code * @param reason the reason phrase, or {@code null} to omit */ void setStatusLine(ProtocolVersion ver, int code, String reason); /** * Updates the status line of this response with a new status code. * * @param code the HTTP status code. * * @throws IllegalStateException * if the status line has not be set * * @see HttpStatus * @see #setStatusLine(StatusLine) * @see #setStatusLine(ProtocolVersion,int) */ void setStatusCode(int code) throws IllegalStateException; /** * Updates the status line of this response with a new reason phrase. * * @param reason the new reason phrase as a single-line string, or * {@code null} to unset the reason phrase * * @throws IllegalStateException * if the status line has not be set * * @see #setStatusLine(StatusLine) * @see #setStatusLine(ProtocolVersion,int) */ void setReasonPhrase(String reason) throws IllegalStateException; /** * Obtains the message entity of this response, if any. * The entity is provided by calling {@link #setEntity setEntity}. * * @return the response entity, or * {@code null} if there is none */ HttpEntity getEntity(); /** * Associates a response entity with this response. *

* Please note that if an entity has already been set for this response and it depends on * an input stream ({@link HttpEntity#isStreaming()} returns {@code true}), * it must be fully consumed in order to ensure release of resources. * * @param entity the entity to associate with this response, or * {@code null} to unset * * @see HttpEntity#isStreaming() * @see 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 {@code null} */ Locale getLocale(); /** * Changes the locale of this response. * * @param loc the new locale */ void setLocale(Locale loc); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HttpVersion.java0100644 0000000 0000000 00000006523 12613456021 026676 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpResponseInterceptor.java0100644 0000000 0000000 00000005232 12613456021 031262 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpClientConnection.java0100644 0000000 0000000 00000007460 12613456021 030510 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code timeout} milliseconds. * @throws IOException if an error happens on the connection */ boolean isResponseAvailable(int timeout) throws IOException; /** * Sends the request line and all headers over the connection. * @param request the request whose headers to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendRequestHeader(HttpRequest request) throws HttpException, IOException; /** * Sends the request entity over the connection. * @param request the request whose entity to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException; /** * Receives the request line and headers of the next response available from * this connection. The caller should examine the HttpResponse object to * find out if it should try to receive a response entity as well. * * @return a new HttpResponse object with status line and headers * initialized. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ HttpResponse receiveResponseHeader() throws HttpException, IOException; /** * Receives the next response entity available from this connection and * attaches it to an existing HttpResponse object. * * @param response the response to attach the entity to * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void receiveResponseEntity(HttpResponse response) throws HttpException, IOException; /** * Writes out all pending buffered data over the open connection. * * @throws IOException in case of an I/O error */ void flush() throws IOException; } ././@LongLink0100644 0000000 0000000 00000000146 12613460515 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/UnsupportedHttpVersionException.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/UnsupportedHttpVersionException.jav0100644 0000000 0000000 00000003433 12613456020 032661 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpResponseFactory.java0100644 0000000 0000000 00000004706 12613456021 030400 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code null} to use the default locale * * @return the new response with an initialized status line */ HttpResponse newHttpResponse(ProtocolVersion ver, int status, HttpContext context); /** * Creates a new response from a status line. * * @param statusline the status line * @param context the context from which to determine the locale * for looking up a reason phrase if the status code * is updated, or * {@code null} to use the default locale * * @return the new response with the argument status line */ HttpResponse newHttpResponse(StatusLine statusline, HttpContext context); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/Header.java0100644 0000000 0000000 00000004735 12613456022 025605 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 in case of a parsing error */ HeaderElement[] getElements() throws ParseException; } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/package-info.java0100644 0000000 0000000 00000003500 12613456021 026725 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/HttpHeaders.java0100644 0000000 0000000 00000016737 12613456020 026633 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpMessage.java0100644 0000000 0000000 00000015612 12613456021 026634 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code name}. */ Header[] getHeaders(String name); /** * Returns the first header with a specified name of this message. Header * values are ignored. If there is more than one matching header in the * message the first element of {@link #getHeaders(String)} is returned. * If there is no matching header in the message {@code null} is * returned. * * @param name the name of the header to return. * @return the first header whose name property equals {@code name} * or {@code null} if no such header could be found. */ Header getFirstHeader(String name); /** * Returns the last header with a specified name of this message. Header values * are ignored. If there is more than one matching header in the message the * last element of {@link #getHeaders(String)} is returned. If there is no * matching header in the message {@code null} is returned. * * @param name the name of the header to return. * @return the last header whose name property equals {@code name}. * or {@code null} if no such header could be found. */ Header getLastHeader(String name); /** * Returns all the headers of this message. Headers are orderd in the sequence * they will be sent over a connection. * * @return all the headers of this message */ Header[] getAllHeaders(); /** * Adds a header to this message. The header will be appended to the end of * the list. * * @param header the header to append. */ void addHeader(Header header); /** * Adds a header to this message. The header will be appended to the end of * the list. * * @param name the name of the header. * @param value the value of the header. */ void addHeader(String name, String value); /** * Overwrites the first header with the same name. The new header will be appended to * the end of the list, if no header with the given name can be found. * * @param header the header to set. */ void setHeader(Header header); /** * Overwrites the first header with the same name. The new header will be appended to * the end of the list, if no header with the given name can be found. * * @param name the name of the header. * @param value the value of the header. */ void setHeader(String name, String value); /** * Overwrites all the headers in the message. * * @param headers the array of headers to set. */ void setHeaders(Header[] headers); /** * Removes a header from this message. * * @param header the header to remove. */ void removeHeader(Header header); /** * Removes all headers with a certain name from this message. * * @param name The name of the headers to remove. */ void removeHeaders(String name); /** * Returns an iterator of all the headers. * * @return Iterator that returns Header objects in the sequence they are * sent over a connection. */ HeaderIterator headerIterator(); /** * Returns an iterator of the headers with a given name. * * @param name the name of the headers over which to iterate, or * {@code null} for all headers * * @return Iterator that returns Header objects with the argument name * in the sequence they are sent over a connection. */ HeaderIterator headerIterator(String name); /** * Returns the parameters effective for this message as set by * {@link #setParams(HttpParams)}. * * @deprecated (4.3) use configuration classes provided '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.4.4/httpcore/src/main/java/org/apache/http/StatusLine.java0100644 0000000 0000000 00000003443 12613456022 026503 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/NameValuePair.java0100644 0000000 0000000 00000003012 12613456022 027071 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/ReasonPhraseCatalog.java0100644 0000000 0000000 00000003400 12613456021 030265 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} if unknown */ String getReason(int status, Locale loc); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ProtocolException.java0100644 0000000 0000000 00000004414 12613456020 030065 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} detail message. */ public ProtocolException() { super(); } /** * Creates a new ProtocolException with the specified detail message. * * @param message The exception detail message */ public ProtocolException(final String message) { super(message); } /** * Creates a new ProtocolException with the specified detail message and cause. * * @param message the exception detail message * @param cause the {@code Throwable} that caused this exception, or {@code null} * if the cause is unavailable, unknown, or not a {@code Throwable} */ public ProtocolException(final String message, final Throwable cause) { super(message, cause); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HeaderElement.java0100644 0000000 0000000 00000006233 12613456016 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; /** * 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.4.4/httpcore/src/main/java/org/apache/http/ConnectionClosedException.java0100644 0000000 0000000 00000003255 12613456020 031517 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/FormattedHeader.java0100644 0000000 0000000 00000004133 12613456022 027443 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpRequestInterceptor.java0100644 0000000 0000000 00000005224 12613456020 031114 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/TruncatedChunkException.java0100644 0000000 0000000 00000003215 12613456016 031211 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/MethodNotSupportedException.java0100644 0000000 0000000 00000004117 12613456022 032075 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Throwable} that caused this exception, or {@code null} * if the cause is unavailable, unknown, or not a {@code Throwable} */ public MethodNotSupportedException(final String message, final Throwable cause) { super(message, cause); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HttpEntityEnclosingRequest.java0100644 0000000 0000000 00000003741 12613456021 031737 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/RequestLine.java0100644 0000000 0000000 00000003223 12613456016 026647 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpConnectionMetrics.java0100644 0000000 0000000 00000004364 12613456021 030700 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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, * {@code null} if the metric cannot not found. */ Object getMetric(String metricName); /** * Resets the counts * */ void reset(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HeaderIterator.java0100644 0000000 0000000 00000003463 12613456016 027317 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code true} if there is another header, * {@code false} otherwise */ @Override boolean hasNext(); /** * Obtains the next header from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next header in this iteration */ Header nextHeader(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ContentTooLongException.java0100644 0000000 0000000 00000003221 12613456021 031174 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/Consts.java0100644 0000000 0000000 00000003473 12613456021 025663 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpRequestFactory.java0100644 0000000 0000000 00000003007 12613456021 030223 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpEntity.java0100644 0000000 0000000 00000017637 12613456021 026535 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code true} if chunked encoding is preferred for this * entity, or {@code false} if it is not */ boolean isChunked(); /** * Tells the length of the content, if known. * * @return the number of bytes of the content, or * a negative number if unknown. If the content length is known * but exceeds {@link java.lang.Long#MAX_VALUE Long.MAX_VALUE}, * a negative number is returned. */ long getContentLength(); /** * Obtains the Content-Type header, if known. * This is the header that should be used when sending the entity, * or the one that was received with the entity. It can include a * charset attribute. * * @return the Content-Type header for this entity, or * {@code null} if the content type is unknown */ Header getContentType(); /** * Obtains the Content-Encoding header, if known. * This is the header that should be used when sending the entity, * or the one that was received with the entity. * Wrapping entities that modify the content encoding should * adjust this header accordingly. * * @return the Content-Encoding header for this entity, or * {@code null} if the content encoding is unknown */ Header getContentEncoding(); /** * Returns a content stream of the entity. * {@link #isRepeatable Repeatable} entities are expected * to create a new instance of {@link InputStream} for each invocation * of this method and therefore can be consumed multiple times. * Entities that are not {@link #isRepeatable repeatable} are expected * to return the same {@link InputStream} instance and therefore * may not be consumed more than once. *

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

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

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

* This method is of particular importance for entities being * received from a {@link HttpConnection connection}. The entity * needs to be consumed completely in order to re-use the connection * with keep-alive. * * @throws IOException if an I/O error occurs. * * @deprecated (4.1) Use {@link org.apache.http.util.EntityUtils#consume(HttpEntity)} * * @see #getContent() and #writeTo(OutputStream) */ @Deprecated void consumeContent() throws IOException; } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ConnectionReuseStrategy.java0100644 0000000 0000000 00000005446 12613456022 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; 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 {@code false}, the caller MUST * close the connection to correctly comply with the HTTP protocol. * If it returns {@code true}, the caller SHOULD attempt to * keep the connection open for reuse with another request. *

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

*

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

* * @param response * The last response received over that connection. * @param context the context in which the connection is being * used. * * @return {@code true} if the connection is allowed to be reused, or * {@code false} if it MUST NOT be reused */ boolean keepAlive(HttpResponse response, HttpContext context); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HttpConnection.java0100644 0000000 0000000 00000007110 12613456021 027341 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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. */ @Override void close() throws IOException; /** * Checks if this connection is open. * @return true if it is open, false if it is closed. */ boolean isOpen(); /** * Checks whether this connection has gone down. * Network connections may get closed during some time of inactivity * for several reasons. The next time a read is attempted on such a * connection it will throw an IOException. * This method tries to alleviate this inconvenience by trying to * find out if a connection is still usable. Implementations may do * that by attempting a read with a very small timeout. Thus this * method may block for a small amount of time before returning a result. * It is therefore an expensive operation. * * @return {@code true} if attempts to use this connection are * likely to succeed, or {@code false} if they are likely * to fail and this connection should be closed */ boolean isStale(); /** * Sets the socket timeout value. * * @param timeout timeout value in milliseconds */ void setSocketTimeout(int timeout); /** * Returns the socket timeout value. * * @return positive value in milliseconds if a timeout is set, * {@code 0} if timeout is disabled or {@code -1} if * timeout is undefined. */ int getSocketTimeout(); /** * Force-closes this connection. * This is the only method of a connection which may be called * from a different thread to terminate the connection. * This method will not attempt to flush the transmitter's * internal buffer prior to closing the underlying socket. */ void shutdown() throws IOException; /** * Returns a collection of connection metrics. * * @return HttpConnectionMetrics */ HttpConnectionMetrics getMetrics(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/NoHttpResponseException.java0100644 0000000 0000000 00000003261 12613456021 031217 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/HttpStatus.java0100644 0000000 0000000 00000017130 12613456021 026530 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 --- /** {@code 100 Continue} (HTTP/1.1 - RFC 2616) */ public static final int SC_CONTINUE = 100; /** {@code 101 Switching Protocols} (HTTP/1.1 - RFC 2616)*/ public static final int SC_SWITCHING_PROTOCOLS = 101; /** {@code 102 Processing} (WebDAV - RFC 2518) */ public static final int SC_PROCESSING = 102; // --- 2xx Success --- /** {@code 200 OK} (HTTP/1.0 - RFC 1945) */ public static final int SC_OK = 200; /** {@code 201 Created} (HTTP/1.0 - RFC 1945) */ public static final int SC_CREATED = 201; /** {@code 202 Accepted} (HTTP/1.0 - RFC 1945) */ public static final int SC_ACCEPTED = 202; /** {@code 203 Non Authoritative Information} (HTTP/1.1 - RFC 2616) */ public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; /** {@code 204 No Content} (HTTP/1.0 - RFC 1945) */ public static final int SC_NO_CONTENT = 204; /** {@code 205 Reset Content} (HTTP/1.1 - RFC 2616) */ public static final int SC_RESET_CONTENT = 205; /** {@code 206 Partial Content} (HTTP/1.1 - RFC 2616) */ public static final int SC_PARTIAL_CONTENT = 206; /** * {@code 207 Multi-Status} (WebDAV - RFC 2518) * or * {@code 207 Partial Update OK} (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?) */ public static final int SC_MULTI_STATUS = 207; // --- 3xx Redirection --- /** {@code 300 Mutliple Choices} (HTTP/1.1 - RFC 2616) */ public static final int SC_MULTIPLE_CHOICES = 300; /** {@code 301 Moved Permanently} (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_PERMANENTLY = 301; /** {@code 302 Moved Temporarily} (Sometimes {@code Found}) (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_TEMPORARILY = 302; /** {@code 303 See Other} (HTTP/1.1 - RFC 2616) */ public static final int SC_SEE_OTHER = 303; /** {@code 304 Not Modified} (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_MODIFIED = 304; /** {@code 305 Use Proxy} (HTTP/1.1 - RFC 2616) */ public static final int SC_USE_PROXY = 305; /** {@code 307 Temporary Redirect} (HTTP/1.1 - RFC 2616) */ public static final int SC_TEMPORARY_REDIRECT = 307; // --- 4xx Client Error --- /** {@code 400 Bad Request} (HTTP/1.1 - RFC 2616) */ public static final int SC_BAD_REQUEST = 400; /** {@code 401 Unauthorized} (HTTP/1.0 - RFC 1945) */ public static final int SC_UNAUTHORIZED = 401; /** {@code 402 Payment Required} (HTTP/1.1 - RFC 2616) */ public static final int SC_PAYMENT_REQUIRED = 402; /** {@code 403 Forbidden} (HTTP/1.0 - RFC 1945) */ public static final int SC_FORBIDDEN = 403; /** {@code 404 Not Found} (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_FOUND = 404; /** {@code 405 Method Not Allowed} (HTTP/1.1 - RFC 2616) */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** {@code 406 Not Acceptable} (HTTP/1.1 - RFC 2616) */ public static final int SC_NOT_ACCEPTABLE = 406; /** {@code 407 Proxy Authentication Required} (HTTP/1.1 - RFC 2616)*/ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** {@code 408 Request Timeout} (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TIMEOUT = 408; /** {@code 409 Conflict} (HTTP/1.1 - RFC 2616) */ public static final int SC_CONFLICT = 409; /** {@code 410 Gone} (HTTP/1.1 - RFC 2616) */ public static final int SC_GONE = 410; /** {@code 411 Length Required} (HTTP/1.1 - RFC 2616) */ public static final int SC_LENGTH_REQUIRED = 411; /** {@code 412 Precondition Failed} (HTTP/1.1 - RFC 2616) */ public static final int SC_PRECONDITION_FAILED = 412; /** {@code 413 Request Entity Too Large} (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TOO_LONG = 413; /** {@code 414 Request-URI Too Long} (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** {@code 415 Unsupported Media Type} (HTTP/1.1 - RFC 2616) */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** {@code 416 Requested Range Not Satisfiable} (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** {@code 417 Expectation Failed} (HTTP/1.1 - RFC 2616) */ public static final int SC_EXPECTATION_FAILED = 417; /** * Static constant for a 418 error. * {@code 418 Unprocessable Entity} (WebDAV drafts?) * or {@code 418 Reauthentication Required} (HTTP/1.1 drafts?) */ // not used // public static final int SC_UNPROCESSABLE_ENTITY = 418; /** * Static constant for a 419 error. * {@code 419 Insufficient Space on Resource} * (WebDAV - draft-ietf-webdav-protocol-05?) * or {@code 419 Proxy Reauthentication Required} * (HTTP/1.1 drafts?) */ public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; /** * Static constant for a 420 error. * {@code 420 Method Failure} * (WebDAV - draft-ietf-webdav-protocol-05?) */ public static final int SC_METHOD_FAILURE = 420; /** {@code 422 Unprocessable Entity} (WebDAV - RFC 2518) */ public static final int SC_UNPROCESSABLE_ENTITY = 422; /** {@code 423 Locked} (WebDAV - RFC 2518) */ public static final int SC_LOCKED = 423; /** {@code 424 Failed Dependency} (WebDAV - RFC 2518) */ public static final int SC_FAILED_DEPENDENCY = 424; // --- 5xx Server Error --- /** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */ public static final int SC_INTERNAL_SERVER_ERROR = 500; /** {@code 501 Not Implemented} (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_IMPLEMENTED = 501; /** {@code 502 Bad Gateway} (HTTP/1.0 - RFC 1945) */ public static final int SC_BAD_GATEWAY = 502; /** {@code 503 Service Unavailable} (HTTP/1.0 - RFC 1945) */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** {@code 504 Gateway Timeout} (HTTP/1.1 - RFC 2616) */ public static final int SC_GATEWAY_TIMEOUT = 504; /** {@code 505 HTTP Version Not Supported} (HTTP/1.1 - RFC 2616) */ public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505; /** {@code 507 Insufficient Storage} (WebDAV - RFC 2518) */ public static final int SC_INSUFFICIENT_STORAGE = 507; } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HeaderElementIterator.java0100644 0000000 0000000 00000003560 12613456020 030622 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code true} if there is another header element, * {@code false} otherwise */ @Override boolean hasNext(); /** * Obtains the next header element from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next header element in this iteration */ HeaderElement nextElement(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ProtocolVersion.java0100644 0000000 0000000 00000021173 12613456020 027555 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code this} * if the version matches, and creates a new {@link ProtocolVersion} * otherwise. *

* * @param major the major version * @param minor the minor version * * @return a protocol version with the same protocol name * and the argument version */ public ProtocolVersion forVersion(final int major, final int minor) { if ((major == this.major) && (minor == this.minor)) { return this; } // argument checking is done in the constructor return new ProtocolVersion(this.protocol, major, minor); } /** * Obtains a hash code consistent with {@link #equals}. * * @return the hashcode of this protocol version */ @Override public final int hashCode() { return this.protocol.hashCode() ^ (this.major * 100000) ^ this.minor; } /** * Checks equality of this protocol version with an object. * The object is equal if it is a protocl version with the same * protocol name, major version number, and minor version number. * The specific class of the object is not relevant, * instances of derived classes with identical attributes are * equal to instances of the base class and vice versa. * * @param obj the object to compare with * * @return {@code true} if the argument is the same protocol version, * {@code false} otherwise */ @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof ProtocolVersion)) { return false; } final ProtocolVersion that = (ProtocolVersion) obj; return ((this.protocol.equals(that.protocol)) && (this.major == that.major) && (this.minor == that.minor)); } /** * Checks whether this protocol can be compared to another one. * Only protocol versions with the same protocol name can be * {@link #compareToVersion compared}. * * @param that the protocol version to consider * * @return {@code true} if {@link #compareToVersion compareToVersion} * can be called with the argument, {@code false} otherwise */ public boolean isComparable(final ProtocolVersion that) { return (that != null) && this.protocol.equals(that.protocol); } /** * Compares this protocol version with another one. * Only protocol versions with the same protocol name can be compared. * This method does not define a total ordering, as it would be * required for {@link java.lang.Comparable}. * * @param that the protocol version to compare with * * @return a negative integer, zero, or a positive integer * as this version is less than, equal to, or greater than * the argument version. * * @throws IllegalArgumentException * if the argument has a different protocol name than this object, * or if the argument is {@code null} */ public int compareToVersion(final ProtocolVersion that) { Args.notNull(that, "Protocol version"); Args.check(this.protocol.equals(that.protocol), "Versions for different protocols cannot be compared: %s %s", this, that); int delta = getMajor() - that.getMajor(); if (delta == 0) { delta = getMinor() - that.getMinor(); } return delta; } /** * Tests if this protocol version is greater or equal to the given one. * * @param version the version against which to check this version * * @return {@code true} if this protocol version is * {@link #isComparable comparable} to the argument * and {@link #compareToVersion compares} as greater or equal, * {@code false} otherwise */ public final boolean greaterEquals(final ProtocolVersion version) { return isComparable(version) && (compareToVersion(version) >= 0); } /** * Tests if this protocol version is less or equal to the given one. * * @param version the version against which to check this version * * @return {@code true} if this protocol version is * {@link #isComparable comparable} to the argument * and {@link #compareToVersion compares} as less or equal, * {@code false} otherwise */ public final boolean lessEquals(final ProtocolVersion version) { return isComparable(version) && (compareToVersion(version) <= 0); } /** * Converts this protocol version to a string. * * @return a protocol version string, like "HTTP/1.1" */ @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append(this.protocol); buffer.append('/'); buffer.append(Integer.toString(this.major)); buffer.append('.'); buffer.append(Integer.toString(this.minor)); return buffer.toString(); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HttpException.java0100644 0000000 0000000 00000004244 12613456022 027206 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} detail message. */ public HttpException() { super(); } /** * Creates a new HttpException with the specified detail message. * * @param message the exception detail message */ public HttpException(final String message) { super(message); } /** * Creates a new HttpException with the specified detail message and cause. * * @param message the exception detail message * @param cause the {@code Throwable} that caused this exception, or {@code null} * if the cause is unavailable, unknown, or not a {@code Throwable} */ public HttpException(final String message, final Throwable cause) { super(message); initCause(cause); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/MessageConstraintException.java0100644 0000000 0000000 00000003511 12613456021 031713 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.CharacterCodingException; /** * Signals a message constraint violation. * * @since 4.3 */ public class MessageConstraintException extends CharacterCodingException { private static final long serialVersionUID = 6077207720446368695L; private final String message; /** * Creates a TruncatedChunkException with the specified detail message. * * @param message The exception detail message */ public MessageConstraintException(final String message) { super(); this.message = message; } @Override public String getMessage() { return this.message; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/HttpConnectionFactory.java0100644 0000000 0000000 00000002673 12613456021 030702 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/MalformedChunkCodingException.java0100644 0000000 0000000 00000003476 12613456016 032323 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/message/0040755 0000000 0000000 00000000000 12613456017 025174 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicLineParser.java0100644 0000000 0000000 00000037114 12613456017 031050 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code null} for HTTP. The actual version * is not relevant, only the protocol name. */ public BasicLineParser(final ProtocolVersion proto) { this.protocol = proto != null? proto : HttpVersion.HTTP_1_1; } /** * Creates a new line parser for HTTP. */ public BasicLineParser() { this(null); } public static ProtocolVersion parseProtocolVersion(final String value, final LineParser parser) throws ParseException { Args.notNull(value, "Value"); final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); final ParserCursor cursor = new ParserCursor(0, value.length()); return (parser != null ? parser : BasicLineParser.INSTANCE) .parseProtocolVersion(buffer, cursor); } // non-javadoc, see interface LineParser @Override public ProtocolVersion parseProtocolVersion(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException { Args.notNull(buffer, "Char array buffer"); Args.notNull(cursor, "Parser cursor"); final String protoname = this.protocol.getProtocol(); final int protolength = protoname.length(); final int indexFrom = cursor.getPos(); final int indexTo = cursor.getUpperBound(); skipWhitespace(buffer, cursor); int i = cursor.getPos(); // long enough for "HTTP/1.1"? if (i + protolength + 4 > indexTo) { throw new ParseException ("Not a valid protocol version: " + buffer.substring(indexFrom, indexTo)); } // check the protocol name and slash boolean ok = true; for (int j=0; ok && (j buffer.length()) { return false; } // just check protocol name and slash, no need to analyse the version boolean ok = true; for (int j=0; ok && (j. * */ package 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 {@code null} * * @return the cleared argument buffer if there is one, or * a new empty buffer that can be used for formatting */ protected CharArrayBuffer initBuffer(final CharArrayBuffer charBuffer) { CharArrayBuffer buffer = charBuffer; if (buffer != null) { buffer.clear(); } else { buffer = new CharArrayBuffer(64); } return buffer; } /** * Formats a protocol version. * * @param version the protocol version to format * @param formatter the formatter to use, or * {@code null} for the * {@link #INSTANCE default} * * @return the formatted protocol version */ public static String formatProtocolVersion(final ProtocolVersion version, final LineFormatter formatter) { return (formatter != null ? formatter : BasicLineFormatter.INSTANCE) .appendProtocolVersion(null, version).toString(); } // non-javadoc, see interface LineFormatter @Override public CharArrayBuffer appendProtocolVersion(final CharArrayBuffer buffer, final ProtocolVersion version) { Args.notNull(version, "Protocol version"); // can't use initBuffer, that would clear the argument! CharArrayBuffer result = buffer; final int len = estimateProtocolVersionLen(version); if (result == null) { result = new CharArrayBuffer(len); } else { result.ensureCapacity(len); } result.append(version.getProtocol()); result.append('/'); result.append(Integer.toString(version.getMajor())); result.append('.'); result.append(Integer.toString(version.getMinor())); return result; } /** * Guesses the length of a formatted protocol version. * Needed to guess the length of a formatted request or status line. * * @param version the protocol version to format, or {@code null} * * @return the estimated length of the formatted protocol version, * in characters */ protected int estimateProtocolVersionLen(final ProtocolVersion version) { return version.getProtocol().length() + 4; // room for "HTTP/1.1" } /** * Formats a request line. * * @param reqline the request line to format * @param formatter the formatter to use, or * {@code null} for the * {@link #INSTANCE default} * * @return the formatted request line */ public static String formatRequestLine(final RequestLine reqline, final LineFormatter formatter) { return (formatter != null ? formatter : BasicLineFormatter.INSTANCE) .formatRequestLine(null, reqline).toString(); } // non-javadoc, see interface LineFormatter @Override public CharArrayBuffer formatRequestLine(final CharArrayBuffer buffer, final RequestLine reqline) { Args.notNull(reqline, "Request line"); final CharArrayBuffer result = initBuffer(buffer); doFormatRequestLine(result, reqline); return result; } /** * Actually formats a request line. * Called from {@link #formatRequestLine}. * * @param buffer the empty buffer into which to format, * never {@code null} * @param reqline the request line to format, never {@code null} */ protected void doFormatRequestLine(final CharArrayBuffer buffer, final RequestLine reqline) { final String method = reqline.getMethod(); final String uri = reqline.getUri(); // room for "GET /index.html HTTP/1.1" final int len = method.length() + 1 + uri.length() + 1 + estimateProtocolVersionLen(reqline.getProtocolVersion()); buffer.ensureCapacity(len); buffer.append(method); buffer.append(' '); buffer.append(uri); buffer.append(' '); appendProtocolVersion(buffer, reqline.getProtocolVersion()); } /** * Formats a status line. * * @param statline the status line to format * @param formatter the formatter to use, or * {@code null} for the * {@link #INSTANCE default} * * @return the formatted status line */ public static String formatStatusLine(final StatusLine statline, final LineFormatter formatter) { return (formatter != null ? formatter : BasicLineFormatter.INSTANCE) .formatStatusLine(null, statline).toString(); } // non-javadoc, see interface LineFormatter @Override public CharArrayBuffer formatStatusLine(final CharArrayBuffer buffer, final StatusLine statline) { Args.notNull(statline, "Status line"); final CharArrayBuffer result = initBuffer(buffer); doFormatStatusLine(result, statline); return result; } /** * Actually formats a status line. * Called from {@link #formatStatusLine}. * * @param buffer the empty buffer into which to format, * never {@code null} * @param statline the status line to format, never {@code null} */ protected void doFormatStatusLine(final CharArrayBuffer buffer, final StatusLine statline) { int len = estimateProtocolVersionLen(statline.getProtocolVersion()) + 1 + 3 + 1; // room for "HTTP/1.1 200 " final String reason = statline.getReasonPhrase(); if (reason != null) { len += reason.length(); } buffer.ensureCapacity(len); appendProtocolVersion(buffer, statline.getProtocolVersion()); buffer.append(' '); buffer.append(Integer.toString(statline.getStatusCode())); buffer.append(' '); // keep whitespace even if reason phrase is empty if (reason != null) { buffer.append(reason); } } /** * Formats a header. * * @param header the header to format * @param formatter the formatter to use, or * {@code null} for the * {@link #INSTANCE default} * * @return the formatted header */ public static String formatHeader(final Header header, final LineFormatter formatter) { return (formatter != null ? formatter : BasicLineFormatter.INSTANCE) .formatHeader(null, header).toString(); } // non-javadoc, see interface LineFormatter @Override public CharArrayBuffer formatHeader(final CharArrayBuffer buffer, final Header header) { Args.notNull(header, "Header"); final CharArrayBuffer result; if (header instanceof FormattedHeader) { // If the header is backed by a buffer, re-use the buffer result = ((FormattedHeader)header).getBuffer(); } else { result = initBuffer(buffer); doFormatHeader(result, header); } return result; } // formatHeader /** * Actually formats a header. * Called from {@link #formatHeader}. * * @param buffer the empty buffer into which to format, * never {@code null} * @param header the header to format, never {@code null} */ protected void doFormatHeader(final CharArrayBuffer buffer, final Header header) { final String name = header.getName(); final String value = header.getValue(); int len = name.length() + 2; if (value != null) { len += value.length(); } buffer.ensureCapacity(len); buffer.append(name); buffer.append(": "); if (value != null) { buffer.append(value); } } } // class BasicLineFormatter ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicListHeaderIterator.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicListHeaderIterator.jav0100644 0000000 0000000 00000012743 12613456017 032402 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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. * {@code null} to iterate over all headers in the array. */ protected String headerName; /** * Creates a new header iterator. * * @param headers a list of headers over which to iterate * @param name the name of the headers over which to iterate, or * {@code null} for any */ public BasicListHeaderIterator(final List
headers, final String name) { super(); this.allHeaders = Args.notNull(headers, "Header list"); this.headerName = name; this.currentIndex = findNext(-1); this.lastIndex = -1; } /** * Determines the index of the next header. * * @param pos one less than the index to consider first, * -1 to search for the first header * * @return the index of the next header that matches the filter name, * or negative if there are no more headers */ protected int findNext(final int pos) { int from = pos; if (from < -1) { return -1; } final int to = this.allHeaders.size()-1; boolean found = false; while (!found && (from < to)) { from++; found = filterHeader(from); } return found ? from : -1; } /** * Checks whether a header is part of the iteration. * * @param index the index of the header to check * * @return {@code true} if the header should be part of the * iteration, {@code false} to skip */ protected boolean filterHeader(final int index) { if (this.headerName == null) { return true; } // non-header elements, including null, will trigger exceptions final String name = (this.allHeaders.get(index)).getName(); return this.headerName.equalsIgnoreCase(name); } // non-javadoc, see interface HeaderIterator @Override public boolean hasNext() { return (this.currentIndex >= 0); } /** * Obtains the next header from this iteration. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ @Override public Header nextHeader() throws NoSuchElementException { final int current = this.currentIndex; if (current < 0) { throw new NoSuchElementException("Iteration already finished."); } this.lastIndex = current; this.currentIndex = findNext(current); return this.allHeaders.get(current); } /** * Returns the next header. * Same as {@link #nextHeader nextHeader}, but not type-safe. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ @Override public final Object next() throws NoSuchElementException { return nextHeader(); } /** * Removes the header that was returned last. */ @Override public void remove() throws UnsupportedOperationException { Asserts.check(this.lastIndex >= 0, "No header to remove"); this.allHeaders.remove(this.lastIndex); this.lastIndex = -1; this.currentIndex--; // adjust for the removed element } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHttpRequest.java0100644 0000000 0000000 00000007131 12613456017 031270 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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) */ @Override public ProtocolVersion getProtocolVersion() { return getRequestLine().getProtocolVersion(); } /** * Returns the request line of this request. * * @see #BasicHttpRequest(String, String) */ @Override public RequestLine getRequestLine() { if (this.requestline == null) { this.requestline = new BasicRequestLine(this.method, this.uri, HttpVersion.HTTP_1_1); } return this.requestline; } @Override public String toString() { return this.method + ' ' + this.uri + ' ' + this.headergroup; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicRequestLine.java0100644 0000000 0000000 00000005154 12613456017 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"); } @Override public String getMethod() { return this.method; } @Override public ProtocolVersion getProtocolVersion() { return this.protoversion; } @Override public String getUri() { return this.uri; } @Override public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.INSTANCE.formatRequestLine(null, this).toString(); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeader.java0100644 0000000 0000000 00000005413 12613456017 030171 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; } @Override public String getName() { return this.name; } @Override public String getValue() { return this.value; } @Override public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.INSTANCE.formatHeader(null, this).toString(); } @Override public HeaderElement[] getElements() throws ParseException { if (this.value != null) { // result intentionally not cached, it's probably not used again return BasicHeaderValueParser.parseElements(this.value, null); } else { return new HeaderElement[] {}; } } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/HeaderValueFormatter.java0100644 0000000 0000000 00000011765 12613456017 032117 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code null} to create a new buffer * @param elems the header elements to format * @param quote {@code true} to always format with quoted values, * {@code false} to use quotes only when necessary * * @return a buffer with the formatted header elements. * If the {@code buffer} argument was not {@code null}, * that buffer will be used and returned. */ CharArrayBuffer formatElements(CharArrayBuffer buffer, HeaderElement[] elems, boolean quote); /** * Formats one header element. * * @param buffer the buffer to append to, or * {@code null} to create a new buffer * @param elem the header element to format * @param quote {@code true} to always format with quoted values, * {@code false} to use quotes only when necessary * * @return a buffer with the formatted header element. * If the {@code buffer} argument was not {@code null}, * that buffer will be used and returned. */ CharArrayBuffer formatHeaderElement(CharArrayBuffer buffer, HeaderElement elem, boolean quote); /** * Formats the parameters of a header element. * That's a list of name-value pairs, to be separated by semicolons. * This method will not generate a leading semicolon. * * @param buffer the buffer to append to, or * {@code null} to create a new buffer * @param nvps the parameters (name-value pairs) to format * @param quote {@code true} to always format with quoted values, * {@code false} to use quotes only when necessary * * @return a buffer with the formatted parameters. * If the {@code buffer} argument was not {@code null}, * that buffer will be used and returned. */ CharArrayBuffer formatParameters(CharArrayBuffer buffer, NameValuePair[] nvps, boolean quote); /** * Formats one name-value pair, where the value is optional. * * @param buffer the buffer to append to, or * {@code null} to create a new buffer * @param nvp the name-value pair to format * @param quote {@code true} to always format with a quoted value, * {@code false} to use quotes only when necessary * * @return a buffer with the formatted name-value pair. * If the {@code buffer} argument was not {@code null}, * that buffer will be used and returned. */ CharArrayBuffer formatNameValuePair(CharArrayBuffer buffer, NameValuePair nvp, boolean quote); } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHttpEntityEnclosingRequest.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHttpEntityEnclosingReq0100644 0000000 0000000 00000005001 12613456017 032500 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override public HttpEntity getEntity() { return this.entity; } @Override public void setEntity(final HttpEntity entity) { this.entity = entity; } @Override public boolean expectContinue() { final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/AbstractHttpMessage.java0100644 0000000 0000000 00000012470 12613456017 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 @Override public boolean containsHeader(final String name) { return this.headergroup.containsHeader(name); } // non-javadoc, see interface HttpMessage @Override public Header[] getHeaders(final String name) { return this.headergroup.getHeaders(name); } // non-javadoc, see interface HttpMessage @Override public Header getFirstHeader(final String name) { return this.headergroup.getFirstHeader(name); } // non-javadoc, see interface HttpMessage @Override public Header getLastHeader(final String name) { return this.headergroup.getLastHeader(name); } // non-javadoc, see interface HttpMessage @Override public Header[] getAllHeaders() { return this.headergroup.getAllHeaders(); } // non-javadoc, see interface HttpMessage @Override public void addHeader(final Header header) { this.headergroup.addHeader(header); } // non-javadoc, see interface HttpMessage @Override public void addHeader(final String name, final String value) { Args.notNull(name, "Header name"); this.headergroup.addHeader(new BasicHeader(name, value)); } // non-javadoc, see interface HttpMessage @Override public void setHeader(final Header header) { this.headergroup.updateHeader(header); } // non-javadoc, see interface HttpMessage @Override public void setHeader(final String name, final String value) { Args.notNull(name, "Header name"); this.headergroup.updateHeader(new BasicHeader(name, value)); } // non-javadoc, see interface HttpMessage @Override public void setHeaders(final Header[] headers) { this.headergroup.setHeaders(headers); } // non-javadoc, see interface HttpMessage @Override public void removeHeader(final Header header) { this.headergroup.removeHeader(header); } // non-javadoc, see interface HttpMessage @Override public void removeHeaders(final String name) { if (name == null) { return; } for (final HeaderIterator i = this.headergroup.iterator(); i.hasNext(); ) { final Header header = i.nextHeader(); if (name.equalsIgnoreCase(header.getName())) { i.remove(); } } } // non-javadoc, see interface HttpMessage @Override public HeaderIterator headerIterator() { return this.headergroup.iterator(); } // non-javadoc, see interface HttpMessage @Override public HeaderIterator headerIterator(final String name) { return this.headergroup.iterator(name); } /** * @deprecated (4.3) use constructor parameters of configuration API provided by HttpClient */ @Override @Deprecated public HttpParams getParams() { if (this.params == null) { this.params = new BasicHttpParams(); } return this.params; } /** * @deprecated (4.3) use constructor parameters of configuration API provided by HttpClient */ @Override @Deprecated public void setParams(final HttpParams params) { this.params = Args.notNull(params, "HTTP parameters"); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/LineFormatter.java0100644 0000000 0000000 00000012257 12613456017 030616 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code formatXXX} methods. * The argument buffer can always be re-used after the call. The buffer * returned as the result, if it is different from the argument buffer, * MUST NOT be modified. *

* * @since 4.0 */ public interface LineFormatter { /** * Formats a protocol version. * This method does not follow the general contract for * {@code buffer} arguments. * It does not clear the argument buffer, but appends instead. * The returned buffer can always be modified by the caller. * Because of these differing conventions, it is not named * {@code formatProtocolVersion}. * * @param buffer a buffer to which to append, or {@code null} * @param version the protocol version to format * * @return a buffer with the formatted protocol version appended. * The caller is allowed to modify the result buffer. * If the {@code buffer} argument is not {@code null}, * the returned buffer is the argument buffer. */ CharArrayBuffer appendProtocolVersion(CharArrayBuffer buffer, ProtocolVersion version); /** * Formats a request line. * * @param buffer a buffer available for formatting, or * {@code null}. * The buffer will be cleared before use. * @param reqline the request line to format * * @return the formatted request line */ CharArrayBuffer formatRequestLine(CharArrayBuffer buffer, RequestLine reqline); /** * Formats a status line. * * @param buffer a buffer available for formatting, or * {@code null}. * The buffer will be cleared before use. * @param statline the status line to format * * @return the formatted status line * * @throws 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 * {@code null}. * The buffer will be cleared before use. * @param header the header to format * * @return a buffer holding the formatted header, never {@code null}. * The returned buffer may be different from the argument buffer. * * @throws org.apache.http.ParseException in case of a parse error */ CharArrayBuffer formatHeader(CharArrayBuffer buffer, Header header); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/package-info.java0100644 0000000 0000000 00000002470 12613456017 030363 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/message/BasicNameValuePair.java0100644 0000000 0000000 00000006467 12613456017 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; } @Override public String getName() { return this.name; } @Override public String getValue() { return this.value; } @Override public String toString() { // don't call complex default formatting for a simple toString if (this.value == null) { return name; } final int len = this.name.length() + 1 + this.value.length(); final StringBuilder buffer = new StringBuilder(len); buffer.append(this.name); buffer.append("="); buffer.append(this.value); return buffer.toString(); } @Override public boolean equals(final Object object) { if (this == object) { return true; } if (object instanceof NameValuePair) { final BasicNameValuePair that = (BasicNameValuePair) object; return this.name.equals(that.name) && LangUtils.equals(this.value, that.value); } return false; } @Override public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.name); hash = LangUtils.hashCode(hash, this.value); return hash; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/LineParser.java0100644 0000000 0000000 00000012351 12613456017 030102 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code true} if there is a protocol version at the * argument index (possibly ignoring whitespace), * {@code false} otherwise */ boolean hasProtocolVersion( CharArrayBuffer buffer, ParserCursor cursor); /** * Parses a request line. * * @param buffer a buffer holding the line to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed request line * * @throws ParseException in case of a parse error */ RequestLine parseRequestLine( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a status line. * * @param buffer a buffer holding the line to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed status line * * @throws ParseException in case of a parse error */ StatusLine parseStatusLine( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Creates a header from a line. * The full header line is expected here. Header continuation lines * must be joined by the caller before invoking this method. * * @param buffer a buffer holding the full header line. * This buffer MUST NOT be re-used afterwards, since * the returned object may reference the contents later. * * @return the header in the argument buffer. * The returned object MAY be a wrapper for the argument buffer. * The argument buffer MUST NOT be re-used or changed afterwards. * * @throws ParseException in case of a parse error */ Header parseHeader(CharArrayBuffer buffer) throws ParseException; } ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeaderValueParser.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeaderValueParser.java0100644 0000000 0000000 00000026164 12613456017 032351 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.BitSet; 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.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 = ','; // IMPORTANT! // These private static variables must be treated as immutable and never exposed outside this class private static final BitSet TOKEN_DELIMS = TokenParser.INIT_BITSET('=', PARAM_DELIMITER, ELEM_DELIMITER); private static final BitSet VALUE_DELIMS = TokenParser.INIT_BITSET(PARAM_DELIMITER, ELEM_DELIMITER); private final TokenParser tokenParser; public BasicHeaderValueParser() { this.tokenParser = TokenParser.INSTANCE; } /** * Parses elements with the given parser. * * @param value the header value to parse * @param parser the parser to use, or {@code null} for default * * @return array holding the header elements, never {@code null} * @throws ParseException in case of a parsing error */ public static HeaderElement[] parseElements(final String value, final HeaderValueParser parser) throws ParseException { Args.notNull(value, "Value"); final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); final ParserCursor cursor = new ParserCursor(0, value.length()); return (parser != null ? parser : BasicHeaderValueParser.INSTANCE) .parseElements(buffer, cursor); } // non-javadoc, see interface HeaderValueParser @Override public HeaderElement[] parseElements(final CharArrayBuffer buffer, final ParserCursor cursor) { Args.notNull(buffer, "Char array buffer"); Args.notNull(cursor, "Parser cursor"); final List elements = new ArrayList(); while (!cursor.atEnd()) { final HeaderElement element = parseHeaderElement(buffer, cursor); if (!(element.getName().length() == 0 && element.getValue() == null)) { elements.add(element); } } return elements.toArray(new HeaderElement[elements.size()]); } /** * Parses an element with the given parser. * * @param value the header element to parse * @param parser the parser to use, or {@code null} for default * * @return the parsed header element */ public static HeaderElement parseHeaderElement(final String value, final HeaderValueParser parser) throws ParseException { Args.notNull(value, "Value"); final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); final ParserCursor cursor = new ParserCursor(0, value.length()); return (parser != null ? parser : BasicHeaderValueParser.INSTANCE) .parseHeaderElement(buffer, cursor); } // non-javadoc, see interface HeaderValueParser @Override public HeaderElement parseHeaderElement(final CharArrayBuffer buffer, final ParserCursor cursor) { Args.notNull(buffer, "Char array buffer"); Args.notNull(cursor, "Parser cursor"); final NameValuePair nvp = parseNameValuePair(buffer, cursor); NameValuePair[] params = null; if (!cursor.atEnd()) { final char ch = buffer.charAt(cursor.getPos() - 1); if (ch != ELEM_DELIMITER) { params = parseParameters(buffer, cursor); } } return createHeaderElement(nvp.getName(), nvp.getValue(), params); } /** * Creates a header element. * Called from {@link #parseHeaderElement}. * * @return a header element representing the argument */ protected HeaderElement createHeaderElement( final String name, final String value, final NameValuePair[] params) { return new BasicHeaderElement(name, value, params); } /** * Parses parameters with the given parser. * * @param value the parameter list to parse * @param parser the parser to use, or {@code null} for default * * @return array holding the parameters, never {@code null} */ public static NameValuePair[] parseParameters(final String value, final HeaderValueParser parser) throws ParseException { Args.notNull(value, "Value"); final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); final ParserCursor cursor = new ParserCursor(0, value.length()); return (parser != null ? parser : BasicHeaderValueParser.INSTANCE) .parseParameters(buffer, cursor); } // non-javadoc, see interface HeaderValueParser @Override public NameValuePair[] parseParameters(final CharArrayBuffer buffer, final ParserCursor cursor) { Args.notNull(buffer, "Char array buffer"); Args.notNull(cursor, "Parser cursor"); tokenParser.skipWhiteSpace(buffer, cursor); final List params = new ArrayList(); while (!cursor.atEnd()) { final NameValuePair param = parseNameValuePair(buffer, cursor); params.add(param); final char ch = buffer.charAt(cursor.getPos() - 1); if (ch == ELEM_DELIMITER) { break; } } return params.toArray(new NameValuePair[params.size()]); } /** * Parses a name-value-pair with the given parser. * * @param value the NVP to parse * @param parser the parser to use, or {@code null} for default * * @return the parsed name-value pair */ public static NameValuePair parseNameValuePair(final String value, final HeaderValueParser parser) throws ParseException { Args.notNull(value, "Value"); final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); final ParserCursor cursor = new ParserCursor(0, value.length()); return (parser != null ? parser : BasicHeaderValueParser.INSTANCE) .parseNameValuePair(buffer, cursor); } // non-javadoc, see interface HeaderValueParser @Override public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor) { Args.notNull(buffer, "Char array buffer"); Args.notNull(cursor, "Parser cursor"); final String name = tokenParser.parseToken(buffer, cursor, TOKEN_DELIMS); if (cursor.atEnd()) { return new BasicNameValuePair(name, null); } final int delim = buffer.charAt(cursor.getPos()); cursor.updatePos(cursor.getPos() + 1); if (delim != '=') { return createNameValuePair(name, null); } final String value = tokenParser.parseValue(buffer, cursor, VALUE_DELIMS); if (!cursor.atEnd()) { cursor.updatePos(cursor.getPos() + 1); } return createNameValuePair(name, value); } /** * @deprecated (4.4) use {@link org.apache.http.message.TokenParser} */ @Deprecated public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor, final char[] delimiters) { Args.notNull(buffer, "Char array buffer"); Args.notNull(cursor, "Parser cursor"); final BitSet delimSet = new BitSet(); if (delimiters != null) { for (char delimiter: delimiters) { delimSet.set(delimiter); } } delimSet.set('='); final String name = tokenParser.parseToken(buffer, cursor, delimSet); if (cursor.atEnd()) { return new BasicNameValuePair(name, null); } final int delim = buffer.charAt(cursor.getPos()); cursor.updatePos(cursor.getPos() + 1); if (delim != '=') { return createNameValuePair(name, null); } delimSet.clear('='); final String value = tokenParser.parseValue(buffer, cursor, delimSet); if (!cursor.atEnd()) { cursor.updatePos(cursor.getPos() + 1); } return createNameValuePair(name, value); } /** * Creates a name-value pair. * Called from {@link #parseNameValuePair}. * * @param name the name * @param value the value, or {@code null} * * @return a name-value pair representing the arguments */ protected NameValuePair createNameValuePair(final String name, final String value) { return new BasicNameValuePair(name, value); } } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeaderValueFormatter.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeaderValueFormatter.j0100644 0000000 0000000 00000033543 12613456017 032367 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code true} to always format with quoted values, * {@code false} to use quotes only when necessary * @param formatter the formatter to use, or {@code null} * for the {@link #INSTANCE default} * * @return the formatted header elements */ public static String formatElements(final HeaderElement[] elems, final boolean quote, final HeaderValueFormatter formatter) { return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE) .formatElements(null, elems, quote).toString(); } // non-javadoc, see interface HeaderValueFormatter @Override public CharArrayBuffer formatElements(final CharArrayBuffer charBuffer, final HeaderElement[] elems, final boolean quote) { Args.notNull(elems, "Header element array"); final int len = estimateElementsLen(elems); CharArrayBuffer buffer = charBuffer; if (buffer == null) { buffer = new CharArrayBuffer(len); } else { buffer.ensureCapacity(len); } for (int i=0; i 0) { buffer.append(", "); } formatHeaderElement(buffer, elems[i], quote); } return buffer; } /** * Estimates the length of formatted header elements. * * @param elems the header elements to format, or {@code null} * * @return a length estimate, in number of characters */ protected int estimateElementsLen(final HeaderElement[] elems) { if ((elems == null) || (elems.length < 1)) { return 0; } int result = (elems.length-1) * 2; // elements separated by ", " for (final HeaderElement elem : elems) { result += estimateHeaderElementLen(elem); } return result; } /** * Formats a header element. * * @param elem the header element to format * @param quote {@code true} to always format with quoted values, * {@code false} to use quotes only when necessary * @param formatter the formatter to use, or {@code null} * for the {@link #INSTANCE default} * * @return the formatted header element */ public static String formatHeaderElement(final HeaderElement elem, final boolean quote, final HeaderValueFormatter formatter) { return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE) .formatHeaderElement(null, elem, quote).toString(); } // non-javadoc, see interface HeaderValueFormatter @Override public CharArrayBuffer formatHeaderElement(final CharArrayBuffer charBuffer, final HeaderElement elem, final boolean quote) { Args.notNull(elem, "Header element"); final int len = estimateHeaderElementLen(elem); CharArrayBuffer buffer = charBuffer; if (buffer == null) { buffer = new CharArrayBuffer(len); } else { buffer.ensureCapacity(len); } buffer.append(elem.getName()); final String value = elem.getValue(); if (value != null) { buffer.append('='); doFormatValue(buffer, value, quote); } final int parcnt = elem.getParameterCount(); if (parcnt > 0) { for (int i=0; i 0) { for (int i=0; i estimateNameValuePairLen(elem.getParameter(i)); } } return result; } /** * Formats a set of parameters. * * @param nvps the parameters to format * @param quote {@code true} to always format with quoted values, * {@code false} to use quotes only when necessary * @param formatter the formatter to use, or {@code null} * for the {@link #INSTANCE default} * * @return the formatted parameters */ public static String formatParameters(final NameValuePair[] nvps, final boolean quote, final HeaderValueFormatter formatter) { return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE) .formatParameters(null, nvps, quote).toString(); } // non-javadoc, see interface HeaderValueFormatter @Override public CharArrayBuffer formatParameters(final CharArrayBuffer charBuffer, final NameValuePair[] nvps, final boolean quote) { Args.notNull(nvps, "Header parameter array"); final int len = estimateParametersLen(nvps); CharArrayBuffer buffer = charBuffer; if (buffer == null) { buffer = new CharArrayBuffer(len); } else { buffer.ensureCapacity(len); } for (int i = 0; i < nvps.length; i++) { if (i > 0) { buffer.append("; "); } formatNameValuePair(buffer, nvps[i], quote); } return buffer; } /** * Estimates the length of formatted parameters. * * @param nvps the parameters to format, or {@code null} * * @return a length estimate, in number of characters */ protected int estimateParametersLen(final NameValuePair[] nvps) { if ((nvps == null) || (nvps.length < 1)) { return 0; } int result = (nvps.length-1) * 2; // "; " between the parameters for (final NameValuePair nvp : nvps) { result += estimateNameValuePairLen(nvp); } return result; } /** * Formats a name-value pair. * * @param nvp the name-value pair to format * @param quote {@code true} to always format with a quoted value, * {@code false} to use quotes only when necessary * @param formatter the formatter to use, or {@code null} * for the {@link #INSTANCE default} * * @return the formatted name-value pair */ public static String formatNameValuePair(final NameValuePair nvp, final boolean quote, final HeaderValueFormatter formatter) { return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE) .formatNameValuePair(null, nvp, quote).toString(); } // non-javadoc, see interface HeaderValueFormatter @Override public CharArrayBuffer formatNameValuePair(final CharArrayBuffer charBuffer, final NameValuePair nvp, final boolean quote) { Args.notNull(nvp, "Name / value pair"); final int len = estimateNameValuePairLen(nvp); CharArrayBuffer buffer = charBuffer; if (buffer == null) { buffer = new CharArrayBuffer(len); } else { buffer.ensureCapacity(len); } buffer.append(nvp.getName()); final String value = nvp.getValue(); if (value != null) { buffer.append('='); doFormatValue(buffer, value, quote); } return buffer; } /** * Estimates the length of a formatted name-value pair. * * @param nvp the name-value pair to format, or {@code null} * * @return a length estimate, in number of characters */ protected int estimateNameValuePairLen(final NameValuePair nvp) { if (nvp == null) { return 0; } int result = nvp.getName().length(); // name final String value = nvp.getValue(); if (value != null) { // assume quotes, but no escaped characters result += 3 + value.length(); // ="value" } return result; } /** * Actually formats the value of a name-value pair. * This does not include a leading = character. * Called from {@link #formatNameValuePair formatNameValuePair}. * * @param buffer the buffer to append to, never {@code null} * @param value the value to append, never {@code null} * @param quote {@code true} to always format with quotes, * {@code false} to use quotes only when necessary */ protected void doFormatValue(final CharArrayBuffer buffer, final String value, final boolean quote) { boolean quoteFlag = quote; if (!quoteFlag) { for (int i = 0; (i < value.length()) && !quoteFlag; i++) { quoteFlag = isSeparator(value.charAt(i)); } } if (quoteFlag) { buffer.append('"'); } for (int i = 0; i < value.length(); i++) { final char ch = value.charAt(i); if (isUnsafe(ch)) { buffer.append('\\'); } buffer.append(ch); } if (quoteFlag) { buffer.append('"'); } } /** * Checks whether a character is a {@link #SEPARATORS separator}. * * @param ch the character to check * * @return {@code true} if the character is a separator, * {@code false} otherwise */ protected boolean isSeparator(final char ch) { return SEPARATORS.indexOf(ch) >= 0; } /** * Checks whether a character is {@link #UNSAFE_CHARS unsafe}. * * @param ch the character to check * * @return {@code true} if the character is unsafe, * {@code false} otherwise */ protected boolean isUnsafe(final char ch) { return UNSAFE_CHARS.indexOf(ch) >= 0; } } // class BasicHeaderValueFormatter httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeaderElement.java0100644 0000000 0000000 00000011704 12613456017 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.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 {@code null} * @param parameters header element parameters. May be {@code null}. * Parameters are copied by reference, not by value */ public BasicHeaderElement( final String name, final String value, final NameValuePair[] parameters) { super(); this.name = Args.notNull(name, "Name"); this.value = value; if (parameters != null) { this.parameters = parameters; } else { this.parameters = new NameValuePair[] {}; } } /** * Constructor with name and value. * * @param name header element name * @param value header element value. May be {@code null} */ public BasicHeaderElement(final String name, final String value) { this(name, value, null); } @Override public String getName() { return this.name; } @Override public String getValue() { return this.value; } @Override public NameValuePair[] getParameters() { return this.parameters.clone(); } @Override public int getParameterCount() { return this.parameters.length; } @Override public NameValuePair getParameter(final int index) { // ArrayIndexOutOfBoundsException is appropriate return this.parameters[index]; } @Override public NameValuePair getParameterByName(final String name) { Args.notNull(name, "Name"); NameValuePair found = null; for (final NameValuePair current : this.parameters) { if (current.getName().equalsIgnoreCase(name)) { found = current; break; } } return found; } @Override public boolean equals(final Object object) { if (this == object) { return true; } if (object instanceof HeaderElement) { final BasicHeaderElement that = (BasicHeaderElement) object; return this.name.equals(that.name) && LangUtils.equals(this.value, that.value) && LangUtils.equals(this.parameters, that.parameters); } else { return false; } } @Override public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.name); hash = LangUtils.hashCode(hash, this.value); for (final NameValuePair parameter : this.parameters) { hash = LangUtils.hashCode(hash, parameter); } return hash; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append(this.name); if (this.value != null) { buffer.append("="); buffer.append(this.value); } for (final NameValuePair parameter : this.parameters) { buffer.append("; "); buffer.append(parameter); } return buffer.toString(); } @Override public Object clone() throws CloneNotSupportedException { // parameters array is considered immutable // no need to make a copy of it return super.clone(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicStatusLine.java0100644 0000000 0000000 00000006460 12613456017 031077 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code null} */ public BasicStatusLine(final ProtocolVersion version, final int statusCode, final String reasonPhrase) { super(); this.protoVersion = Args.notNull(version, "Version"); this.statusCode = Args.notNegative(statusCode, "Status code"); this.reasonPhrase = reasonPhrase; } // --------------------------------------------------------- Public Methods @Override public int getStatusCode() { return this.statusCode; } @Override public ProtocolVersion getProtocolVersion() { return this.protoVersion; } @Override public String getReasonPhrase() { return this.reasonPhrase; } @Override public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.INSTANCE.formatStatusLine(null, this).toString(); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/HeaderGroup.java0100644 0000000 0000000 00000023300 12613456017 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.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; private final Header[] EMPTY = new Header[] {}; /** The list of headers for this group, in the order in which they were added */ private final List
headers; /** * Constructor for HeaderGroup. */ public HeaderGroup() { this.headers = new ArrayList
(16); } /** * Removes any contained headers. */ public void clear() { headers.clear(); } /** * Adds the given header to the group. The order in which this header was * added is preserved. * * @param header the header to add */ public void addHeader(final Header header) { if (header == null) { return; } headers.add(header); } /** * Removes the given header. * * @param header the header to remove */ public void removeHeader(final Header header) { if (header == null) { return; } headers.remove(header); } /** * Replaces the first occurence of the header with the same name. If no header with * the same name is found the given header is added to the end of the list. * * @param header the new header that should replace the first header with the same * name if present in the list. */ public void updateHeader(final Header header) { if (header == null) { return; } // HTTPCORE-361 : we don't use the for-each syntax, i.e. // for (Header header : headers) // as that creates an Iterator that needs to be garbage-collected for (int i = 0; i < this.headers.size(); i++) { final Header current = this.headers.get(i); if (current.getName().equalsIgnoreCase(header.getName())) { this.headers.set(i, header); return; } } this.headers.add(header); } /** * Sets all of the headers contained within this group overriding any * existing headers. The headers are added in the order in which they appear * in the array. * * @param headers the headers to set */ public void setHeaders(final Header[] headers) { clear(); if (headers == null) { return; } Collections.addAll(this.headers, headers); } /** * Gets a header representing all of the header values with the given name. * If more that one header with the given name exists the values will be * combined with a "," as per RFC 2616. * *

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

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

headersFound = null; // 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)) { if (headersFound == null) { headersFound = new ArrayList
(); } headersFound.add(header); } } return headersFound != null ? headersFound.toArray(new Header[headersFound.size()]) : EMPTY; } /** * Gets the first header with the given name. * *

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

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

Header name comparison is case insensitive. * * @param name the header name to test for * @return {@code true} if at least one header with the name is * contained, {@code false} otherwise */ public boolean containsHeader(final String name) { // HTTPCORE-361 : we don't use the for-each syntax, i.e. // for (Header header : headers) // as that creates an Iterator that needs to be garbage-collected for (int i = 0; i < this.headers.size(); i++) { final Header header = this.headers.get(i); if (header.getName().equalsIgnoreCase(name)) { return true; } } return false; } /** * Returns an iterator over this group of headers. * * @return iterator over this group of headers. * * @since 4.0 */ public HeaderIterator iterator() { return new BasicListHeaderIterator(this.headers, null); } /** * Returns an iterator over the headers with a given name in this group. * * @param name the name of the headers over which to iterate, or * {@code null} for all headers * * @return iterator over some headers in this group. * * @since 4.0 */ public HeaderIterator iterator(final String name) { return new BasicListHeaderIterator(this.headers, name); } /** * Returns a copy of this object * * @return copy of this object * * @since 4.0 */ public HeaderGroup copy() { final HeaderGroup clone = new HeaderGroup(); clone.headers.addAll(this.headers); return clone; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return this.headers.toString(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHttpResponse.java0100644 0000000 0000000 00000017302 12613456017 031437 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code null} to disable automatic * reason phrase lookup * @param locale the locale for looking up reason phrases, or * {@code null} for the system locale */ public BasicHttpResponse(final StatusLine statusline, final ReasonPhraseCatalog catalog, final Locale locale) { super(); this.statusline = Args.notNull(statusline, "Status line"); this.ver = statusline.getProtocolVersion(); this.code = statusline.getStatusCode(); this.reasonPhrase = statusline.getReasonPhrase(); this.reasonCatalog = catalog; this.locale = locale; } /** * Creates a response from a status line. * The response will not have a reason phrase catalog and * use the system default locale. * * @param statusline the status line */ public BasicHttpResponse(final StatusLine statusline) { super(); this.statusline = Args.notNull(statusline, "Status line"); this.ver = statusline.getProtocolVersion(); this.code = statusline.getStatusCode(); this.reasonPhrase = statusline.getReasonPhrase(); this.reasonCatalog = null; this.locale = null; } /** * Creates a response from elements of a status line. * The response will not have a reason phrase catalog and * use the system default locale. * * @param ver the protocol version of the response * @param code the status code of the response * @param reason the reason phrase to the status code, or * {@code null} */ public BasicHttpResponse(final ProtocolVersion ver, final int code, final String reason) { super(); Args.notNegative(code, "Status code"); this.statusline = null; this.ver = ver; this.code = code; this.reasonPhrase = reason; this.reasonCatalog = null; this.locale = null; } // non-javadoc, see interface HttpMessage @Override public ProtocolVersion getProtocolVersion() { return this.ver; } // non-javadoc, see interface HttpResponse @Override public StatusLine getStatusLine() { if (this.statusline == null) { this.statusline = new BasicStatusLine( this.ver != null ? this.ver : HttpVersion.HTTP_1_1, this.code, this.reasonPhrase != null ? this.reasonPhrase : getReason(this.code)); } return this.statusline; } // non-javadoc, see interface HttpResponse @Override public HttpEntity getEntity() { return this.entity; } @Override public Locale getLocale() { return this.locale; } // non-javadoc, see interface HttpResponse @Override public void setStatusLine(final StatusLine statusline) { this.statusline = Args.notNull(statusline, "Status line"); this.ver = statusline.getProtocolVersion(); this.code = statusline.getStatusCode(); this.reasonPhrase = statusline.getReasonPhrase(); } // non-javadoc, see interface HttpResponse @Override public void setStatusLine(final ProtocolVersion ver, final int code) { Args.notNegative(code, "Status code"); this.statusline = null; this.ver = ver; this.code = code; this.reasonPhrase = null; } // non-javadoc, see interface HttpResponse @Override public void setStatusLine( final ProtocolVersion ver, final int code, final String reason) { Args.notNegative(code, "Status code"); this.statusline = null; this.ver = ver; this.code = code; this.reasonPhrase = reason; } // non-javadoc, see interface HttpResponse @Override public void setStatusCode(final int code) { Args.notNegative(code, "Status code"); this.statusline = null; this.code = code; this.reasonPhrase = null; } // non-javadoc, see interface HttpResponse @Override public void setReasonPhrase(final String reason) { this.statusline = null; this.reasonPhrase = reason; } // non-javadoc, see interface HttpResponse @Override public void setEntity(final HttpEntity entity) { this.entity = entity; } @Override public void setLocale(final Locale locale) { this.locale = Args.notNull(locale, "Locale"); this.statusline = null; } /** * Looks up a reason phrase. * This method evaluates the currently set catalog and locale. * It also handles a missing catalog. * * @param code the status code for which to look up the reason * * @return the reason phrase, or {@code null} if there is none */ protected String getReason(final int code) { return this.reasonCatalog != null ? this.reasonCatalog.getReason(code, this.locale != null ? this.locale : Locale.getDefault()) : null; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(getStatusLine()); sb.append(' '); sb.append(this.headergroup); if (this.entity != null) { sb.append(' '); sb.append(this.entity); } return sb.toString(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/HeaderValueParser.java0100644 0000000 0000000 00000012043 12613456017 031376 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code RuntimeException}. *

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

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

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

* * @param buffer buffer holding the header value to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return an array holding all elements of the header value * * @throws ParseException in case of a parsing error */ HeaderElement[] parseElements( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a single header element. * A header element consist of a semicolon-separate list * of name=value definitions. * * @param buffer buffer holding the element to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed element * * @throws ParseException in case of a parse error */ HeaderElement parseHeaderElement( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a list of name-value pairs. * These lists are used to specify parameters to a header element. * Parse errors are indicated as {@code ParseException}. * * @param buffer buffer holding the name-value list to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return an array holding all items of the name-value list * * @throws ParseException in case of a parse error */ NameValuePair[] parseParameters( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a name=value specification, where the = and value are optional. * * @param buffer the buffer holding the name-value pair to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the name-value pair, where the value is {@code null} * if no value is specified */ NameValuePair parseNameValuePair( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; } ././@LongLink0100644 0000000 0000000 00000000151 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeaderElementIterator.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeaderElementIterator.0100644 0000000 0000000 00000012276 12613456017 032360 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.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; } } } } @Override public boolean hasNext() { if (this.currentElement == null) { parseNextElement(); } return this.currentElement != null; } @Override public HeaderElement nextElement() throws NoSuchElementException { if (this.currentElement == null) { parseNextElement(); } if (this.currentElement == null) { throw new NoSuchElementException("No more header elements available"); } final HeaderElement element = this.currentElement; this.currentElement = null; return element; } @Override public final Object next() throws NoSuchElementException { return nextElement(); } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("Remove not supported"); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BufferedHeader.java0100644 0000000 0000000 00000007632 12613456017 030677 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; } @Override public String getName() { return this.name; } @Override public String getValue() { return this.buffer.substringTrimmed(this.valuePos, this.buffer.length()); } @Override public HeaderElement[] getElements() throws ParseException { final ParserCursor cursor = new ParserCursor(0, this.buffer.length()); cursor.updatePos(this.valuePos); return BasicHeaderValueParser.INSTANCE.parseElements(this.buffer, cursor); } @Override public int getValuePos() { return this.valuePos; } @Override public CharArrayBuffer getBuffer() { return this.buffer; } @Override public String toString() { return this.buffer.toString(); } @Override public Object clone() throws CloneNotSupportedException { // buffer is considered immutable // no need to make a copy of it return super.clone(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicHeaderIterator.java0100644 0000000 0000000 00000012114 12613456017 031677 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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. * {@code null} to iterate over all headers in the array. */ protected String headerName; /** * Creates a new header iterator. * * @param headers an array of headers over which to iterate * @param name the name of the headers over which to iterate, or * {@code null} for any */ public BasicHeaderIterator(final Header[] headers, final String name) { super(); this.allHeaders = Args.notNull(headers, "Header array"); this.headerName = name; this.currentIndex = findNext(-1); } /** * Determines the index of the next header. * * @param pos one less than the index to consider first, * -1 to search for the first header * * @return the index of the next header that matches the filter name, * or negative if there are no more headers */ protected int findNext(final int pos) { int from = pos; if (from < -1) { return -1; } final int to = this.allHeaders.length-1; boolean found = false; while (!found && (from < to)) { from++; found = filterHeader(from); } return found ? from : -1; } /** * Checks whether a header is part of the iteration. * * @param index the index of the header to check * * @return {@code true} if the header should be part of the * iteration, {@code false} to skip */ protected boolean filterHeader(final int index) { return (this.headerName == null) || this.headerName.equalsIgnoreCase(this.allHeaders[index].getName()); } // non-javadoc, see interface HeaderIterator @Override public boolean hasNext() { return (this.currentIndex >= 0); } /** * Obtains the next header from this iteration. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ @Override public Header nextHeader() throws NoSuchElementException { final int current = this.currentIndex; if (current < 0) { throw new NoSuchElementException("Iteration already finished."); } this.currentIndex = findNext(current); return this.allHeaders[current]; } /** * Returns the next header. * Same as {@link #nextHeader nextHeader}, but not type-safe. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ @Override public final Object next() throws NoSuchElementException { return nextHeader(); } /** * Removing headers is not supported. * * @throws UnsupportedOperationException always */ @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException ("Removing headers is not supported."); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/BasicTokenIterator.java0100644 0000000 0000000 00000034271 12613456017 031577 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code #token} sequences as * defined by RFC 2616, section 2. * It extends that definition somewhat beyond US-ASCII. * * @since 4.0 */ @NotThreadSafe public class BasicTokenIterator implements TokenIterator { /** The HTTP separator characters. Defined in RFC 2616, section 2.2. */ // the order of the characters here is adjusted to put the // most likely candidates at the beginning of the collection public final static String HTTP_SEPARATORS = " ,;=()<>@:\\\"/[]?{}\t"; /** The iterator from which to obtain the next header. */ protected final HeaderIterator headerIt; /** * The value of the current header. * This is the header value that includes {@link #currentToken}. * Undefined if the iteration is over. */ protected String currentHeader; /** * The token to be returned by the next call to {@link #nextToken()}. * {@code null} if the iteration is over. */ protected String currentToken; /** * The position after {@link #currentToken} in {@link #currentHeader}. * Undefined if the iteration is over. */ protected int searchPos; /** * Creates a new instance of {@link BasicTokenIterator}. * * @param headerIterator the iterator for the headers to tokenize */ public BasicTokenIterator(final HeaderIterator headerIterator) { super(); this.headerIt = Args.notNull(headerIterator, "Header iterator"); this.searchPos = findNext(-1); } // non-javadoc, see interface TokenIterator @Override public boolean hasNext() { return (this.currentToken != null); } /** * Obtains the next token from this iteration. * * @return the next token in this iteration * * @throws NoSuchElementException if the iteration is already over * @throws ParseException if an invalid header value is encountered */ @Override public String nextToken() throws NoSuchElementException, ParseException { if (this.currentToken == null) { throw new NoSuchElementException("Iteration already finished."); } final String result = this.currentToken; // updates currentToken, may trigger ParseException: this.searchPos = findNext(this.searchPos); return result; } /** * Returns the next token. * Same as {@link #nextToken}, but with generic return type. * * @return the next token in this iteration * * @throws NoSuchElementException if there are no more tokens * @throws ParseException if an invalid header value is encountered */ @Override public final Object next() throws NoSuchElementException, ParseException { return nextToken(); } /** * Removing tokens is not supported. * * @throws UnsupportedOperationException always */ @Override public final void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException ("Removing tokens is not supported."); } /** * Determines the next token. * If found, the token is stored in {@link #currentToken}. * The return value indicates the position after the token * in {@link #currentHeader}. If necessary, the next header * will be obtained from {@link #headerIt}. * If not found, {@link #currentToken} is set to {@code null}. * * @param pos the position in the current header at which to * start the search, -1 to search in the first header * * @return the position after the found token in the current header, or * negative if there was no next token * * @throws ParseException if an invalid header value is encountered */ protected int findNext(final int pos) throws ParseException { int from = pos; if (from < 0) { // called from the constructor, initialize the first header if (!this.headerIt.hasNext()) { return -1; } this.currentHeader = this.headerIt.nextHeader().getValue(); from = 0; } else { // called after a token, make sure there is a separator from = findTokenSeparator(from); } final int start = findTokenStart(from); if (start < 0) { this.currentToken = null; return -1; // nothing found } final int end = findTokenEnd(start); this.currentToken = createToken(this.currentHeader, start, end); return end; } /** * Creates a new token to be returned. * Called from {@link #findNext findNext} after the token is identified. * The default implementation simply calls * {@link java.lang.String#substring String.substring}. *

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

* * @param value the full header value from which to create a token * @param start the index of the first token character * @param end the index after the last token character * * @return a string representing the token identified by the arguments */ protected String createToken(final String value, final int start, final int end) { return value.substring(start, end); } /** * Determines the starting position of the next token. * This method will iterate over headers if necessary. * * @param pos the position in the current header at which to * start the search * * @return the position of the token start in the current header, * negative if no token start could be found */ protected int findTokenStart(final int pos) { int from = Args.notNegative(pos, "Search position"); boolean found = false; while (!found && (this.currentHeader != null)) { final int to = this.currentHeader.length(); while (!found && (from < to)) { final char ch = this.currentHeader.charAt(from); if (isTokenSeparator(ch) || isWhitespace(ch)) { // whitspace and token separators are skipped from++; } else if (isTokenChar(this.currentHeader.charAt(from))) { // found the start of a token found = true; } else { throw new ParseException ("Invalid character before token (pos " + from + "): " + this.currentHeader); } } if (!found) { if (this.headerIt.hasNext()) { this.currentHeader = this.headerIt.nextHeader().getValue(); from = 0; } else { this.currentHeader = null; } } } // while headers return found ? from : -1; } /** * Determines the position of the next token separator. * Because of multi-header joining rules, the end of a * header value is a token separator. This method does * therefore not need to iterate over headers. * * @param pos the position in the current header at which to * start the search * * @return the position of a token separator in the current header, * or at the end * * @throws ParseException * if a new token is found before a token separator. * RFC 2616, section 2.1 explicitly requires a comma between * tokens for {@code #}. */ protected int findTokenSeparator(final int pos) { int from = Args.notNegative(pos, "Search position"); boolean found = false; final int to = this.currentHeader.length(); while (!found && (from < to)) { final char ch = this.currentHeader.charAt(from); if (isTokenSeparator(ch)) { found = true; } else if (isWhitespace(ch)) { from++; } else if (isTokenChar(ch)) { throw new ParseException ("Tokens without separator (pos " + from + "): " + this.currentHeader); } else { throw new ParseException ("Invalid character after token (pos " + from + "): " + this.currentHeader); } } return from; } /** * Determines the ending position of the current token. * This method will not leave the current header value, * since the end of the header value is a token boundary. * * @param from the position of the first character of the token * * @return the position after the last character of the token. * The behavior is undefined if {@code from} does not * point to a token character in the current header value. */ protected int findTokenEnd(final int from) { Args.notNegative(from, "Search position"); final int to = this.currentHeader.length(); int end = from+1; while ((end < to) && isTokenChar(this.currentHeader.charAt(end))) { end++; } return end; } /** * Checks whether a character is a token separator. * RFC 2616, section 2.1 defines comma as the separator for * {@code #token} sequences. The end of a header value will * also separate tokens, but that is not a character check. * * @param ch the character to check * * @return {@code true} if the character is a token separator, * {@code false} otherwise */ protected boolean isTokenSeparator(final char ch) { return (ch == ','); } /** * Checks whether a character is a whitespace character. * RFC 2616, section 2.2 defines space and horizontal tab as whitespace. * The optional preceeding line break is irrelevant, since header * continuation is handled transparently when parsing messages. * * @param ch the character to check * * @return {@code true} if the character is whitespace, * {@code false} otherwise */ protected boolean isWhitespace(final char ch) { // we do not use Character.isWhitspace(ch) here, since that allows // many control characters which are not whitespace as per RFC 2616 return ((ch == '\t') || Character.isSpaceChar(ch)); } /** * Checks whether a character is a valid token character. * Whitespace, control characters, and HTTP separators are not * valid token characters. The HTTP specification (RFC 2616, section 2.2) * defines tokens only for the US-ASCII character set, this * method extends the definition to other character sets. * * @param ch the character to check * * @return {@code true} if the character is a valid token start, * {@code false} otherwise */ protected boolean isTokenChar(final char ch) { // common sense extension of ALPHA + DIGIT if (Character.isLetterOrDigit(ch)) { return true; } // common sense extension of CTL if (Character.isISOControl(ch)) { return false; } // no common sense extension for this if (isHttpSeparator(ch)) { return false; } // RFC 2616, section 2.2 defines a token character as // "any CHAR except CTLs or separators". The controls // and separators are included in the checks above. // This will yield unexpected results for Unicode format characters. // If that is a problem, overwrite isHttpSeparator(char) to filter // out the false positives. return true; } /** * Checks whether a character is an HTTP separator. * The implementation in this class checks only for the HTTP separators * defined in RFC 2616, section 2.2. If you need to detect other * separators beyond the US-ASCII character set, override this method. * * @param ch the character to check * * @return {@code true} if the character is an HTTP separator */ protected boolean isHttpSeparator(final char ch) { return (HTTP_SEPARATORS.indexOf(ch) >= 0); } } // class BasicTokenIterator httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/message/ParserCursor.java0100644 0000000 0000000 00000006167 12613456017 030500 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/message/TokenParser.java0100644 0000000 0000000 00000023214 12613456017 030273 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.BitSet; import org.apache.http.annotation.Immutable; import org.apache.http.util.CharArrayBuffer; /** * Low level parser for header field elements. The parsing routines of this class are designed * to produce near zero intermediate garbage and make no intermediate copies of input data. *

* This class is immutable and thread safe. * * @since 4.4 */ @Immutable public class TokenParser { public static BitSet INIT_BITSET(final int ... b) { final BitSet bitset = new BitSet(); for (final int aB : b) { bitset.set(aB); } return bitset; } /** US-ASCII CR, carriage return (13) */ public static final char CR = '\r'; /** US-ASCII LF, line feed (10) */ public static final char LF = '\n'; /** US-ASCII SP, space (32) */ public static final char SP = ' '; /** US-ASCII HT, horizontal-tab (9) */ public static final char HT = '\t'; /** Double quote */ public static final char DQUOTE = '\"'; /** Backward slash / escape character */ public static final char ESCAPE = '\\'; public static boolean isWhitespace(final char ch) { return ch == SP || ch == HT || ch == CR || ch == LF; } public static final TokenParser INSTANCE = new TokenParser(); /** * Extracts from the sequence of chars a token terminated with any of the given delimiters * discarding semantically insignificant whitespace characters. * * @param buf buffer with the sequence of chars to be parsed * @param cursor defines the bounds and current position of the buffer * @param delimiters set of delimiting characters. Can be {@code null} if the token * is not delimited by any character. */ public String parseToken(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) { final StringBuilder dst = new StringBuilder(); boolean whitespace = false; while (!cursor.atEnd()) { final char current = buf.charAt(cursor.getPos()); if (delimiters != null && delimiters.get(current)) { break; } else if (isWhitespace(current)) { skipWhiteSpace(buf, cursor); whitespace = true; } else { if (whitespace && dst.length() > 0) { dst.append(' '); } copyContent(buf, cursor, delimiters, dst); whitespace = false; } } return dst.toString(); } /** * Extracts from the sequence of chars a value which can be enclosed in quote marks and * terminated with any of the given delimiters discarding semantically insignificant * whitespace characters. * * @param buf buffer with the sequence of chars to be parsed * @param cursor defines the bounds and current position of the buffer * @param delimiters set of delimiting characters. Can be {@code null} if the value * is not delimited by any character. */ public String parseValue(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) { final StringBuilder dst = new StringBuilder(); boolean whitespace = false; while (!cursor.atEnd()) { final char current = buf.charAt(cursor.getPos()); if (delimiters != null && delimiters.get(current)) { break; } else if (isWhitespace(current)) { skipWhiteSpace(buf, cursor); whitespace = true; } else if (current == DQUOTE) { if (whitespace && dst.length() > 0) { dst.append(' '); } copyQuotedContent(buf, cursor, dst); whitespace = false; } else { if (whitespace && dst.length() > 0) { dst.append(' '); } copyUnquotedContent(buf, cursor, delimiters, dst); whitespace = false; } } return dst.toString(); } /** * Skips semantically insignificant whitespace characters and moves the cursor to the closest * non-whitespace character. * * @param buf buffer with the sequence of chars to be parsed * @param cursor defines the bounds and current position of the buffer */ public void skipWhiteSpace(final CharArrayBuffer buf, final ParserCursor cursor) { int pos = cursor.getPos(); final int indexFrom = cursor.getPos(); final int indexTo = cursor.getUpperBound(); for (int i = indexFrom; i < indexTo; i++) { final char current = buf.charAt(i); if (!isWhitespace(current)) { break; } else { pos++; } } cursor.updatePos(pos); } /** * Transfers content into the destination buffer until a whitespace character or any of * the given delimiters is encountered. * * @param buf buffer with the sequence of chars to be parsed * @param cursor defines the bounds and current position of the buffer * @param delimiters set of delimiting characters. Can be {@code null} if the value * is delimited by a whitespace only. * @param dst destination buffer */ public void copyContent(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters, final StringBuilder dst) { int pos = cursor.getPos(); final int indexFrom = cursor.getPos(); final int indexTo = cursor.getUpperBound(); for (int i = indexFrom; i < indexTo; i++) { final char current = buf.charAt(i); if ((delimiters != null && delimiters.get(current)) || isWhitespace(current)) { break; } else { pos++; dst.append(current); } } cursor.updatePos(pos); } /** * Transfers content into the destination buffer until a whitespace character, a quote, * or any of the given delimiters is encountered. * * @param buf buffer with the sequence of chars to be parsed * @param cursor defines the bounds and current position of the buffer * @param delimiters set of delimiting characters. Can be {@code null} if the value * is delimited by a whitespace or a quote only. * @param dst destination buffer */ public void copyUnquotedContent(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters, final StringBuilder dst) { int pos = cursor.getPos(); final int indexFrom = cursor.getPos(); final int indexTo = cursor.getUpperBound(); for (int i = indexFrom; i < indexTo; i++) { final char current = buf.charAt(i); if ((delimiters != null && delimiters.get(current)) || isWhitespace(current) || current == DQUOTE) { break; } else { pos++; dst.append(current); } } cursor.updatePos(pos); } /** * Transfers content enclosed with quote marks into the destination buffer. * * @param buf buffer with the sequence of chars to be parsed * @param cursor defines the bounds and current position of the buffer * @param dst destination buffer */ public void copyQuotedContent(final CharArrayBuffer buf, final ParserCursor cursor, final StringBuilder dst) { if (cursor.atEnd()) { return; } int pos = cursor.getPos(); int indexFrom = cursor.getPos(); final int indexTo = cursor.getUpperBound(); char current = buf.charAt(pos); if (current != DQUOTE) { return; } pos++; indexFrom++; boolean escaped = false; for (int i = indexFrom; i < indexTo; i++, pos++) { current = buf.charAt(i); if (escaped) { if (current != DQUOTE && current != ESCAPE) { dst.append(ESCAPE); } dst.append(current); escaped = false; } else { if (current == DQUOTE) { pos++; break; } if (current == ESCAPE) { escaped = true; } else if (current != CR && current != LF) { dst.append(current); } } } cursor.updatePos(pos); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/concurrent/0040755 0000000 0000000 00000000000 12613456016 025731 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/concurrent/package-info.java0100644 0000000 0000000 00000002347 12613456016 031123 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/concurrent/FutureCallback.java0100644 0000000 0000000 00000003003 12613456016 031454 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/concurrent/Cancellable.java0100644 0000000 0000000 00000002556 12613456016 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.concurrent; /** * A {@code Cancellable} represents a process or an operation that can be * canceled. * * @since 4.2 */ public interface Cancellable { boolean cancel(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/concurrent/BasicFuture.java0100644 0000000 0000000 00000011365 12613456016 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. {@code BasicFuture} * can be put into a completed state by invoking any of the following methods: * {@link #cancel()}, {@link #failed(Exception)}, or {@link #completed(Object)}. * * @param the future result type of an asynchronous operation. * @since 4.2 */ public class BasicFuture implements Future, Cancellable { private final FutureCallback callback; private volatile boolean completed; private volatile boolean cancelled; private volatile T result; private volatile Exception ex; public BasicFuture(final FutureCallback callback) { super(); this.callback = callback; } @Override public boolean isCancelled() { return this.cancelled; } @Override public boolean isDone() { return this.completed; } private T getResult() throws ExecutionException { if (this.ex != null) { throw new ExecutionException(this.ex); } return this.result; } @Override public synchronized T get() throws InterruptedException, ExecutionException { while (!this.completed) { wait(); } return getResult(); } @Override public synchronized T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Args.notNull(unit, "Time unit"); final long msecs = unit.toMillis(timeout); final long startTime = (msecs <= 0) ? 0 : System.currentTimeMillis(); long waitTime = msecs; if (this.completed) { return getResult(); } else if (waitTime <= 0) { throw new TimeoutException(); } else { for (;;) { wait(waitTime); if (this.completed) { return getResult(); } else { waitTime = msecs - (System.currentTimeMillis() - startTime); if (waitTime <= 0) { throw new TimeoutException(); } } } } } public boolean completed(final T result) { synchronized(this) { if (this.completed) { return false; } this.completed = true; this.result = result; notifyAll(); } if (this.callback != null) { this.callback.completed(result); } return true; } public boolean failed(final Exception exception) { synchronized(this) { if (this.completed) { return false; } this.completed = true; this.ex = exception; notifyAll(); } if (this.callback != null) { this.callback.failed(exception); } return true; } @Override public boolean cancel(final boolean mayInterruptIfRunning) { synchronized(this) { if (this.completed) { return false; } this.completed = true; this.cancelled = true; notifyAll(); } if (this.callback != null) { this.callback.cancelled(); } return true; } @Override public boolean cancel() { return cancel(true); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/annotation/0040755 0000000 0000000 00000000000 12613456022 025716 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/annotation/GuardedBy.java0100644 0000000 0000000 00000006037 12613456022 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.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The field or method to which this annotation is applied can only be accessed * when holding a particular lock, which may be a built-in (synchronization) lock, * or may be an explicit java.util.concurrent.Lock. * *

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

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

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

*/ @Documented @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.CLASS) // The original version used RUNTIME public @interface GuardedBy { String value(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/annotation/NotThreadSafe.java0100644 0000000 0000000 00000004100 12613456022 031240 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/annotation/package-info.java0100644 0000000 0000000 00000002541 12613456022 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 * . * */ /** * 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.4.4/httpcore/src/main/java/org/apache/http/annotation/ThreadSafe.java0100644 0000000 0000000 00000004217 12613456022 030570 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/annotation/Immutable.java0100644 0000000 0000000 00000005057 12613456022 030504 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/annotation/Obsolete.java0100644 0000000 0000000 00000003316 12613456022 030335 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 is marked as implementing * requirements of the HTTP protocol or a related protocol that are now obsolete. */ @Documented @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.CLASS) public @interface Obsolete { } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/annotation/Experimental.java0100644 0000000 0000000 00000003156 12613456022 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.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The field or method to which this annotation is applied is marked as experimental. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.CLASS) public @interface Experimental { } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/params/0040755 0000000 0000000 00000000000 12613456021 025026 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/params/CoreProtocolPNames.java0100644 0000000 0000000 00000012312 12613456021 031403 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code User-Agent} header. *

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

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

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

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

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

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

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

* *

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

* *

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

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

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

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

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

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

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

* * This parameter expects a value of type {@link java.nio.charset.CodingErrorAction} * * @since 4.2 */ public static final String HTTP_UNMAPPABLE_INPUT_ACTION = "http.unmappable.input.action"; } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/params/HttpParams.java0100644 0000000 0000000 00000014676 12613456021 027767 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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, * {@code null} if the parameter is not set or if it * is explicitly set to {@code null} * * @see #setParameter(String, Object) */ Object getParameter(String name); /** * Assigns the value to the parameter with the given name. * * @param name parameter name * @param value parameter value */ HttpParams setParameter(String name, Object value); /** * Creates a copy of these parameters. * * @return a new set of parameters holding the same values as this one */ HttpParams copy(); /** * Removes the parameter with the specified name. * * @param name parameter name * * @return true if the parameter existed and has been removed, false else. */ boolean removeParameter(String name); /** * Returns a {@link Long} parameter value with the given name. * If the parameter is not explicitly set, the default value is returned. * * @param name the parent name. * @param defaultValue the default value. * * @return a {@link Long} that represents the value of the parameter. * * @see #setLongParameter(String, long) */ long getLongParameter(String name, long defaultValue); /** * Assigns a {@link Long} to the parameter with the given name * * @param name parameter name * @param value parameter value */ HttpParams setLongParameter(String name, long value); /** * Returns an {@link Integer} parameter value with the given name. * If the parameter is not explicitly set, the default value is returned. * * @param name the parent name. * @param defaultValue the default value. * * @return a {@link Integer} that represents the value of the parameter. * * @see #setIntParameter(String, int) */ int getIntParameter(String name, int defaultValue); /** * Assigns an {@link Integer} to the parameter with the given name * * @param name parameter name * @param value parameter value */ HttpParams setIntParameter(String name, int value); /** * Returns a {@link Double} parameter value with the given name. * If the parameter is not explicitly set, the default value is returned. * * @param name the parent name. * @param defaultValue the default value. * * @return a {@link Double} that represents the value of the parameter. * * @see #setDoubleParameter(String, double) */ double getDoubleParameter(String name, double defaultValue); /** * Assigns a {@link Double} to the parameter with the given name * * @param name parameter name * @param value parameter value */ HttpParams setDoubleParameter(String name, double value); /** * Returns a {@link Boolean} parameter value with the given name. * If the parameter is not explicitly set, the default value is returned. * * @param name the parent name. * @param defaultValue the default value. * * @return a {@link Boolean} that represents the value of the parameter. * * @see #setBooleanParameter(String, boolean) */ boolean getBooleanParameter(String name, boolean defaultValue); /** * Assigns a {@link Boolean} to the parameter with the given name * * @param name parameter name * @param value parameter value */ HttpParams setBooleanParameter(String name, boolean value); /** * Checks if a boolean parameter is set to {@code true}. * * @param name parameter name * * @return {@code true} if the parameter is set to value {@code true}, * {@code false} if it is not set or set to {@code false} */ boolean isParameterTrue(String name); /** * Checks if a boolean parameter is not set or {@code false}. * * @param name parameter name * * @return {@code true} if the parameter is either not set or * set to value {@code false}, * {@code false} if it is set to {@code true} */ boolean isParameterFalse(String name); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/params/HttpParamsNames.java0100644 0000000 0000000 00000003527 12613456021 030744 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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<String> */ Set getNames(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/params/package-info.java0100644 0000000 0000000 00000002356 12613456021 030220 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/params/AbstractHttpParams.java0100644 0000000 0000000 00000010015 12613456021 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.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(); } @Override public long getLongParameter(final String name, final long defaultValue) { final Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Long) param).longValue(); } @Override public HttpParams setLongParameter(final String name, final long value) { setParameter(name, Long.valueOf(value)); return this; } @Override public int getIntParameter(final String name, final int defaultValue) { final Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Integer) param).intValue(); } @Override public HttpParams setIntParameter(final String name, final int value) { setParameter(name, Integer.valueOf(value)); return this; } @Override public double getDoubleParameter(final String name, final double defaultValue) { final Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Double) param).doubleValue(); } @Override public HttpParams setDoubleParameter(final String name, final double value) { setParameter(name, Double.valueOf(value)); return this; } @Override public boolean getBooleanParameter(final String name, final boolean defaultValue) { final Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Boolean) param).booleanValue(); } @Override public HttpParams setBooleanParameter(final String name, final boolean value) { setParameter(name, value ? Boolean.TRUE : Boolean.FALSE); return this; } @Override public boolean isParameterTrue(final String name) { return getBooleanParameter(name, false); } @Override public boolean isParameterFalse(final String name) { return !getBooleanParameter(name, false); } /** * {@inheritDoc} *

* Dummy implementation - must be overridden by subclasses. * * @since 4.2 * @throws UnsupportedOperationException - always */ @Override public Set getNames(){ throw new UnsupportedOperationException(); } } // class AbstractHttpParams httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/params/CoreConnectionPNames.java0100644 0000000 0000000 00000015037 12613456021 031710 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 ({@code SO_TIMEOUT}) in milliseconds, * which is the timeout for waiting for data or, put differently, * a maximum period inactivity between two consecutive data packets). * A timeout value of zero is interpreted as an infinite timeout. *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* @see java.net.SocketOptions#SO_KEEPALIVE * @since 4.2 */ public static final String SO_KEEPALIVE = "http.socket.keepalive"; } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/params/HttpParamConfig.java0100644 0000000 0000000 00000006533 12613456021 030723 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/params/BasicHttpParams.java0100644 0000000 0000000 00000013404 12613456021 030715 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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(); } @Override public Object getParameter(final String name) { return this.parameters.get(name); } @Override public HttpParams setParameter(final String name, final Object value) { if (name == null) { return this; } if (value != null) { this.parameters.put(name, value); } else { this.parameters.remove(name); } return this; } @Override public boolean removeParameter(final String name) { //this is to avoid the case in which the key has a null value if (this.parameters.containsKey(name)) { this.parameters.remove(name); return true; } else { return false; } } /** * Assigns the value to all the parameter with the given names * * @param names array of parameter names * @param value parameter value */ public void setParameters(final String[] names, final Object value) { for (final String name : names) { setParameter(name, value); } } /** * Is the parameter set? *

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

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

* The parameter value is fetched directly. *

* Also @see {@link #isParameterSet(String)} * * @param name parameter name * @return true if parameter is defined and non-null */ public boolean isParameterSetLocally(final String name) { return this.parameters.get(name) != null; } /** * Removes all parameters from this collection. */ public void clear() { this.parameters.clear(); } /** * Creates a copy of these parameters. * This implementation calls {@link #clone()}. * * @return a new set of params holding a copy of the * local parameters in this object. * * @throws UnsupportedOperationException if the clone() fails */ @Override public HttpParams copy() { try { return (HttpParams) clone(); } catch (final CloneNotSupportedException ex) { throw new UnsupportedOperationException("Cloning not supported"); } } /** * Clones the instance. * Uses {@link #copyParams(HttpParams)} to copy the parameters. */ @Override public Object clone() throws CloneNotSupportedException { final BasicHttpParams clone = (BasicHttpParams) super.clone(); copyParams(clone); return clone; } /** * Copies the locally defined parameters to the argument parameters. * This method is called from {@link #clone()}. * * @param target the parameters to which to copy * @since 4.2 */ public void copyParams(final HttpParams target) { for (final Map.Entry me : this.parameters.entrySet()) { target.setParameter(me.getKey(), me.getValue()); } } /** * Returns the current set of names. * * Changes to the underlying HttpParams are not reflected * in the set - it is a snapshot. * * @return the names, as a Set<String> * @since 4.2 */ @Override public Set getNames() { return new HashSet(this.parameters.keySet()); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/0040755 0000000 0000000 00000000000 12613456021 025404 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/BasicHttpContext.java0100644 0000000 0000000 00000005377 12613456021 031506 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; } @Override public Object getAttribute(final String id) { Args.notNull(id, "Id"); Object obj = this.map.get(id); if (obj == null && this.parentContext != null) { obj = this.parentContext.getAttribute(id); } return obj; } @Override public void setAttribute(final String id, final Object obj) { Args.notNull(id, "Id"); if (obj != null) { this.map.put(id, obj); } else { this.map.remove(id); } } @Override public Object removeAttribute(final String id) { Args.notNull(id, "Id"); return this.map.remove(id); } /** * @since 4.2 */ public void clear() { this.map.clear(); } @Override public String toString() { return this.map.toString(); } } ././@LongLink0100644 0000000 0000000 00000000152 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandlerResolver.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandlerResolver0100644 0000000 0000000 00000003476 12613456021 032646 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} if no match * is found. */ HttpRequestHandler lookup(String requestURI); } ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/RequestExpectContinue.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/RequestExpectContinue.java0100644 0000000 0000000 00000006674 12613456021 032567 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Expect} header. This interceptor is * recommended for client side protocol processors. * * @since 4.0 */ @Immutable @SuppressWarnings("deprecation") public class RequestExpectContinue implements HttpRequestInterceptor { private final boolean activeByDefault; /** * @deprecated (4.3) use {@link org.apache.http.protocol.RequestExpectContinue#RequestExpectContinue(boolean)} */ @Deprecated public RequestExpectContinue() { this(false); } /** * @since 4.3 */ public RequestExpectContinue(final boolean activeByDefault) { super(); this.activeByDefault = activeByDefault; } @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) { if (request instanceof HttpEntityEnclosingRequest) { final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); // Do not send the expect header if request body is known to be empty if (entity != null && entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) { final boolean active = request.getParams().getBooleanParameter( CoreProtocolPNames.USE_EXPECT_CONTINUE, this.activeByDefault); if (active) { request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); } } } } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpRequestExecutor.java0100644 0000000 0000000 00000027572 12613456021 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.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; /** * {@code HttpRequestExecutor} is a client side HTTP protocol handler based * on the blocking (classic) I/O model. *

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

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

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

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

* This method does not read the response entity, if any. * The connection over which content of the response entity is being * streamed from cannot be reused until * {@link 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 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/RequestDate.java0100644 0000000 0000000 00000004472 12613456021 030501 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Date} header * to the outgoing requests This interceptor is optional for client side * protocol processors. * * @since 4.0 */ @ThreadSafe public class RequestDate implements HttpRequestInterceptor { private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator(); public RequestDate() { super(); } @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); if ((request instanceof HttpEntityEnclosingRequest) && !request.containsHeader(HTTP.DATE_HEADER)) { final String httpdate = DATE_GENERATOR.getCurrentDate(); request.setHeader(HTTP.DATE_HEADER, httpdate); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/UriPatternMatcher.java0100644 0000000 0000000 00000011630 12613456021 031646 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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: *

    *
  • {@code *}
  • *
  • {@code *<uri>}
  • *
  • {@code <uri>*}
  • *
*
* This class can be used to resolve an object matching a particular request * URI. * * @since 4.0 */ @ThreadSafe public class UriPatternMatcher { @GuardedBy("this") private final Map map; public UriPatternMatcher() { super(); this.map = new HashMap(); } /** * Registers the given object for URIs matching the given pattern. * * @param pattern the pattern to register the handler for. * @param obj the object. */ public synchronized void register(final String pattern, final T obj) { Args.notNull(pattern, "URI request pattern"); this.map.put(pattern, obj); } /** * Removes registered object, if exists, for the given pattern. * * @param pattern the pattern to unregister. */ public synchronized void unregister(final String pattern) { if (pattern == null) { return; } this.map.remove(pattern); } /** * @deprecated (4.1) do not use */ @Deprecated public synchronized void setHandlers(final Map map) { Args.notNull(map, "Map of handlers"); this.map.clear(); this.map.putAll(map); } /** * @deprecated (4.1) do not use */ @Deprecated public synchronized void setObjects(final Map map) { Args.notNull(map, "Map of handlers"); this.map.clear(); this.map.putAll(map); } /** * @deprecated (4.1) do not use */ @Deprecated public synchronized Map getObjects() { return this.map; } /** * Looks up an object matching the given request path. * * @param path the request path * @return object or {@code null} if no match is found. */ public synchronized T lookup(final String path) { Args.notNull(path, "Request path"); // direct match? T obj = this.map.get(path); if (obj == null) { // pattern match? String bestMatch = null; for (final String pattern : this.map.keySet()) { if (matchUriRequestPattern(pattern, path)) { // we have a match. is it any better? if (bestMatch == null || (bestMatch.length() < pattern.length()) || (bestMatch.length() == pattern.length() && pattern.endsWith("*"))) { obj = this.map.get(pattern); bestMatch = pattern; } } } } return obj; } /** * Tests if the given request path matches the given pattern. * * @param pattern the pattern * @param path the request path * @return {@code true} if the request URI matches the pattern, * {@code false} otherwise. */ protected boolean matchUriRequestPattern(final String pattern, final String path) { if (pattern.equals("*")) { return true; } else { return (pattern.endsWith("*") && path.startsWith(pattern.substring(0, pattern.length() - 1))) || (pattern.startsWith("*") && path.endsWith(pattern.substring(1, pattern.length()))); } } @Override public String toString() { return this.map.toString(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpProcessor.java0100644 0000000 0000000 00000004420 12613456021 031063 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/protocol/ChainBuilder.java0100644 0000000 0000000 00000006571 12613456021 030606 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpProcessorBuilder.java0100644 0000000 0000000 00000011022 12613456021 032366 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/protocol/package-info.java0100644 0000000 0000000 00000002474 12613456021 030577 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/protocol/ResponseConnControl.java0100644 0000000 0000000 00000010424 12613456021 032222 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Connection} header * to the outgoing responses, which is essential for managing persistence of * {@code HTTP/1.0} connections. This interceptor is recommended for * server side protocol processors. * * @since 4.0 */ @Immutable public class ResponseConnControl implements HttpResponseInterceptor { public ResponseConnControl() { super(); } @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { Args.notNull(response, "HTTP response"); final HttpCoreContext corecontext = HttpCoreContext.adapt(context); // Always drop connection after certain type of responses final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_BAD_REQUEST || status == HttpStatus.SC_REQUEST_TIMEOUT || status == HttpStatus.SC_LENGTH_REQUIRED || status == HttpStatus.SC_REQUEST_TOO_LONG || status == HttpStatus.SC_REQUEST_URI_TOO_LONG || status == HttpStatus.SC_SERVICE_UNAVAILABLE || status == HttpStatus.SC_NOT_IMPLEMENTED) { response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); return; } final Header explicit = response.getFirstHeader(HTTP.CONN_DIRECTIVE); if (explicit != null && HTTP.CONN_CLOSE.equalsIgnoreCase(explicit.getValue())) { // Connection persistence explicitly disabled return; } // Always drop connection for HTTP/1.0 responses and below // if the content body cannot be correctly delimited final HttpEntity entity = response.getEntity(); if (entity != null) { final ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); if (entity.getContentLength() < 0 && (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) { response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); return; } } // Drop connection if requested by the client or request was <= 1.0 final HttpRequest request = corecontext.getRequest(); if (request != null) { final Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE); if (header != null) { response.setHeader(HTTP.CONN_DIRECTIVE, header.getValue()); } else if (request.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) { response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); } } } } ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/ImmutableHttpProcessor.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/ImmutableHttpProcessor.jav0100644 0000000 0000000 00000013035 12613456021 032564 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override public void process( final HttpRequest request, final HttpContext context) throws IOException, HttpException { for (final HttpRequestInterceptor requestInterceptor : this.requestInterceptors) { requestInterceptor.process(request, context); } } @Override public void process( final HttpResponse response, final HttpContext context) throws IOException, HttpException { for (final HttpResponseInterceptor responseInterceptor : this.responseInterceptors) { responseInterceptor.process(response, context); } } } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpResponseInterceptorList.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpResponseInterceptorLis0100644 0000000 0000000 00000006466 12613456021 032665 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code null} if the index is out of range */ HttpResponseInterceptor getResponseInterceptor(int index); /** * Removes all response interceptors from this list. */ void clearResponseInterceptors(); /** * Removes all response interceptor of the specified class * * @param clazz the class of the instances to be removed. */ void removeResponseInterceptorByClass(Class clazz); /** * Sets the response interceptors in this list. * This list will be cleared and re-initialized to contain * all response interceptors from the argument list. * If the argument list includes elements that are not response * interceptors, the behavior is implementation dependent. * * @param list the list of response interceptors */ void setInterceptors(List list); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpDateGenerator.java0100644 0000000 0000000 00000005023 12613456021 031630 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 00000000152 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpRequestInterceptorList.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpRequestInterceptorList0100644 0000000 0000000 00000006435 12613456021 032677 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code null} if the index is out of range */ HttpRequestInterceptor getRequestInterceptor(int index); /** * Removes all request interceptors from this list. */ void clearRequestInterceptors(); /** * Removes all request interceptor of the specified class * * @param clazz the class of the instances to be removed. */ void removeRequestInterceptorByClass(Class clazz); /** * Sets the request interceptors in this list. * This list will be cleared and re-initialized to contain * all request interceptors from the argument list. * If the argument list includes elements that are not request * interceptors, the behavior is implementation dependent. * * @param list the list of request interceptors */ void setInterceptors(List list); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpContext.java0100644 0000000 0000000 00000005304 12613456021 030532 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} if not set. */ Object getAttribute(String id); /** * Sets value of the attribute with the given name. * * @param id the attribute name. * @param obj the attribute value. */ void setAttribute(String id, Object obj); /** * Removes attribute with the given name from the context. * * @param id the attribute name. * @return attribute value, or {@code null} if not set. */ Object removeAttribute(String id); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/ResponseServer.java0100644 0000000 0000000 00000004455 12613456021 031241 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Server} header. This * interceptor is recommended for server side protocol processors. * * @since 4.0 */ @Immutable public class ResponseServer implements HttpResponseInterceptor { private final String originServer; /** * @since 4.3 */ public ResponseServer(final String originServer) { super(); this.originServer = originServer; } public ResponseServer() { this(null); } @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { Args.notNull(response, "HTTP response"); if (!response.containsHeader(HTTP.SERVER_HEADER)) { if (this.originServer != null) { response.addHeader(HTTP.SERVER_HEADER, this.originServer); } } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpCoreContext.java0100644 0000000 0000000 00000011467 12613456021 031352 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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(); } @Override public Object getAttribute(final String id) { return context.getAttribute(id); } @Override public void setAttribute(final String id, final Object obj) { context.setAttribute(id, obj); } @Override public Object removeAttribute(final String id) { return context.removeAttribute(id); } public T getAttribute(final String attribname, final Class clazz) { Args.notNull(clazz, "Attribute class"); final Object obj = getAttribute(attribname); if (obj == null) { return null; } return clazz.cast(obj); } public T getConnection(final Class clazz) { return getAttribute(HTTP_CONNECTION, clazz); } public HttpConnection getConnection() { return getAttribute(HTTP_CONNECTION, HttpConnection.class); } public HttpRequest getRequest() { return getAttribute(HTTP_REQUEST, HttpRequest.class); } public boolean isRequestSent() { final Boolean b = getAttribute(HTTP_REQ_SENT, Boolean.class); return b != null && b.booleanValue(); } public HttpResponse getResponse() { return getAttribute(HTTP_RESPONSE, HttpResponse.class); } public void setTargetHost(final HttpHost host) { setAttribute(HTTP_TARGET_HOST, host); } public HttpHost getTargetHost() { return getAttribute(HTTP_TARGET_HOST, HttpHost.class); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpExpectationVerifier.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpExpectationVerifier.ja0100644 0000000 0000000 00000006265 12613456021 032545 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code 200}. In this case the client will not have to transmit * the request body. If the request meets expectations this method can * terminate without modifying the response object. Per default the status * code of the response object will be set to {@code 100}. * * @param request the HTTP request. * @param response the HTTP response. * @param context the HTTP context. * @throws HttpException in case of an HTTP protocol violation. */ void verify(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException; } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandlerMapper.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandlerMapper.j0100644 0000000 0000000 00000003420 12613456021 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.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 {@code null} if no match * is found. */ HttpRequestHandler lookup(HttpRequest request); } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/UriHttpRequestHandlerMapper.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/UriHttpRequestHandlerMappe0100644 0000000 0000000 00000007521 12613456021 032562 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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: *

    *
  • {@code *}
  • *
  • {@code *<uri>}
  • *
  • {@code <uri>*}
  • *
*
* This class can be used to map an instance of * {@link HttpRequestHandler} matching a particular request URI. Usually the * mapped request handler will be used to process the request with the * specified request URI. * * @since 4.3 */ @ThreadSafe // provided injected dependencies are thread-safe public class UriHttpRequestHandlerMapper implements HttpRequestHandlerMapper { private final UriPatternMatcher matcher; protected UriHttpRequestHandlerMapper(final UriPatternMatcher matcher) { super(); this.matcher = Args.notNull(matcher, "Pattern matcher"); } public UriHttpRequestHandlerMapper() { this(new UriPatternMatcher()); } /** * Registers the given {@link HttpRequestHandler} as a handler for URIs * matching the given pattern. * * @param pattern the pattern to register the handler for. * @param handler the handler. */ public void register(final String pattern, final HttpRequestHandler handler) { Args.notNull(pattern, "Pattern"); Args.notNull(handler, "Handler"); matcher.register(pattern, handler); } /** * Removes registered handler, if exists, for the given pattern. * * @param pattern the pattern to unregister the handler for. */ public void unregister(final String pattern) { matcher.unregister(pattern); } /** * Extracts request path from the given {@link HttpRequest} */ protected String getRequestPath(final HttpRequest request) { String uriPath = request.getRequestLine().getUri(); int index = uriPath.indexOf("?"); if (index != -1) { uriPath = uriPath.substring(0, index); } else { index = uriPath.indexOf("#"); if (index != -1) { uriPath = uriPath.substring(0, index); } } return uriPath; } /** * Looks up a handler matching the given request URI. * * @param request the request * @return handler or {@code null} if no match is found. */ @Override public HttpRequestHandler lookup(final HttpRequest request) { Args.notNull(request, "HTTP request"); return matcher.lookup(getRequestPath(request)); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HTTP.java0100644 0000000 0000000 00000010360 12613456021 027023 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpRequestHandler.java0100644 0000000 0000000 00000004532 12613456021 032036 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/protocol/RequestTargetHost.java0100644 0000000 0000000 00000007172 12613456021 031710 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Host} header. This * interceptor is required for client side protocol processors. * * @since 4.0 */ @Immutable public class RequestTargetHost implements HttpRequestInterceptor { public RequestTargetHost() { super(); } @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); final HttpCoreContext corecontext = HttpCoreContext.adapt(context); final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT") && ver.lessEquals(HttpVersion.HTTP_1_0)) { return; } if (!request.containsHeader(HTTP.TARGET_HOST)) { HttpHost targethost = corecontext.getTargetHost(); if (targethost == null) { final HttpConnection conn = corecontext.getConnection(); if (conn instanceof HttpInetConnection) { // Populate the context with a default HTTP host based on the // inet address of the target host final InetAddress address = ((HttpInetConnection) conn).getRemoteAddress(); final int port = ((HttpInetConnection) conn).getRemotePort(); if (address != null) { targethost = new HttpHost(address.getHostName(), port); } } if (targethost == null) { if (ver.lessEquals(HttpVersion.HTTP_1_0)) { return; } else { throw new ProtocolException("Target host missing"); } } } request.addHeader(HTTP.TARGET_HOST, targethost.toHostString()); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/ResponseContent.java0100644 0000000 0000000 00000012603 12613456021 031377 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code Content-Length} or {@code Transfer-Content} headers based * on the properties of the enclosed entity and the protocol version. * This interceptor is required for correct functioning of server side protocol * processors. * * @since 4.0 */ @Immutable public class ResponseContent implements HttpResponseInterceptor { private final boolean overwrite; /** * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding} * will cause the interceptor to throw {@link ProtocolException} if already present in the * response message. */ public ResponseContent() { this(false); } /** * Constructor that can be used to fine-tune behavior of this interceptor. * * @param overwrite If set to {@code true} the {@code Content-Length} and * {@code Transfer-Encoding} headers will be created or updated if already present. * If set to {@code false} the {@code Content-Length} and * {@code Transfer-Encoding} headers will cause the interceptor to throw * {@link ProtocolException} if already present in the response message. * * @since 4.2 */ public ResponseContent(final boolean overwrite) { super(); this.overwrite = overwrite; } /** * Processes the response (possibly updating or inserting) Content-Length and Transfer-Encoding headers. * @param response The HttpResponse to modify. * @param context Unused. * @throws ProtocolException If either the Content-Length or Transfer-Encoding headers are found. * @throws IllegalArgumentException If the response is null. */ @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { Args.notNull(response, "HTTP response"); if (this.overwrite) { response.removeHeaders(HTTP.TRANSFER_ENCODING); response.removeHeaders(HTTP.CONTENT_LEN); } else { if (response.containsHeader(HTTP.TRANSFER_ENCODING)) { throw new ProtocolException("Transfer-encoding header already present"); } if (response.containsHeader(HTTP.CONTENT_LEN)) { throw new ProtocolException("Content-Length header already present"); } } final ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); final HttpEntity entity = response.getEntity(); if (entity != null) { final long len = entity.getContentLength(); if (entity.isChunked() && !ver.lessEquals(HttpVersion.HTTP_1_0)) { response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); } else if (len >= 0) { response.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength())); } // Specify a content type if known if (entity.getContentType() != null && !response.containsHeader( HTTP.CONTENT_TYPE )) { response.addHeader(entity.getContentType()); } // Specify a content encoding if known if (entity.getContentEncoding() != null && !response.containsHeader( HTTP.CONTENT_ENCODING)) { response.addHeader(entity.getContentEncoding()); } } else { final int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT) { response.addHeader(HTTP.CONTENT_LEN, "0"); } } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/RequestUserAgent.java0100644 0000000 0000000 00000005175 12613456021 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.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 {@code User-Agent} header. * This interceptor is recommended for client side protocol processors. * * @since 4.0 */ @SuppressWarnings("deprecation") @Immutable public class RequestUserAgent implements HttpRequestInterceptor { private final String userAgent; public RequestUserAgent(final String userAgent) { super(); this.userAgent = userAgent; } public RequestUserAgent() { this(null); } @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); if (!request.containsHeader(HTTP.USER_AGENT)) { String s = null; final HttpParams params = request.getParams(); if (params != null) { s = (String) params.getParameter(CoreProtocolPNames.USER_AGENT); } if (s == null) { s = this.userAgent; } if (s != null) { request.addHeader(HTTP.USER_AGENT, s); } } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/HttpService.java0100644 0000000 0000000 00000043235 12613456021 030513 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; /** * {@code HttpService} is a server side HTTP protocol handler based on * the classic (blocking) I/O model. *

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

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

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

* Super-classes can override this method in order to provide a custom * implementation of the request processing logic. * * @param request the HTTP request. * @param response the HTTP response. * @param context the execution context. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ protected void doService( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpRequestHandler handler = null; if (this.handlerMapper != null) { handler = this.handlerMapper.lookup(request); } if (handler != null) { handler.handle(request, response, context); } else { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } } /** * Adaptor class to transition from HttpRequestHandlerResolver to HttpRequestHandlerMapper. */ @Deprecated private static class HttpRequestHandlerResolverAdapter implements HttpRequestHandlerMapper { private final HttpRequestHandlerResolver resolver; public HttpRequestHandlerResolverAdapter(final HttpRequestHandlerResolver resolver) { this.resolver = resolver; } @Override public HttpRequestHandler lookup(final HttpRequest request) { return resolver.lookup(request.getRequestLine().getUri()); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/RequestConnControl.java0100644 0000000 0000000 00000004621 12613456021 032056 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Connection} header * to the outgoing requests, which is essential for managing persistence of * {@code HTTP/1.0} connections. This interceptor is recommended for * client side protocol processors. * * @since 4.0 */ @Immutable public class RequestConnControl implements HttpRequestInterceptor { public RequestConnControl() { super(); } @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT")) { return; } if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) { // Default policy is to keep connection alive // whenever possible request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/ResponseDate.java0100644 0000000 0000000 00000004541 12613456021 030644 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Date} header to the * outgoing responses. This interceptor is recommended for server side protocol * processors. * * @since 4.0 */ @ThreadSafe public class ResponseDate implements HttpResponseInterceptor { private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator(); public ResponseDate() { super(); } @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { Args.notNull(response, "HTTP response"); final int status = response.getStatusLine().getStatusCode(); if ((status >= HttpStatus.SC_OK) && !response.containsHeader(HTTP.DATE_HEADER)) { final String httpdate = DATE_GENERATOR.getCurrentDate(); response.setHeader(HTTP.DATE_HEADER, httpdate); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/protocol/RequestContent.java0100644 0000000 0000000 00000012156 12613456021 031234 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code Content-Length} or {@code Transfer-Content} headers based * on the properties of the enclosed entity and the protocol version. * This interceptor is required for correct functioning of client side protocol * processors. * * @since 4.0 */ @Immutable public class RequestContent implements HttpRequestInterceptor { private final boolean overwrite; /** * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding} * will cause the interceptor to throw {@link ProtocolException} if already present in the * response message. */ public RequestContent() { this(false); } /** * Constructor that can be used to fine-tune behavior of this interceptor. * * @param overwrite If set to {@code true} the {@code Content-Length} and * {@code Transfer-Encoding} headers will be created or updated if already present. * If set to {@code false} the {@code Content-Length} and * {@code Transfer-Encoding} headers will cause the interceptor to throw * {@link ProtocolException} if already present in the response message. * * @since 4.2 */ public RequestContent(final boolean overwrite) { super(); this.overwrite = overwrite; } @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); if (request instanceof HttpEntityEnclosingRequest) { if (this.overwrite) { request.removeHeaders(HTTP.TRANSFER_ENCODING); request.removeHeaders(HTTP.CONTENT_LEN); } else { if (request.containsHeader(HTTP.TRANSFER_ENCODING)) { throw new ProtocolException("Transfer-encoding header already present"); } if (request.containsHeader(HTTP.CONTENT_LEN)) { throw new ProtocolException("Content-Length header already present"); } } final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); if (entity == null) { request.addHeader(HTTP.CONTENT_LEN, "0"); return; } // Must specify a transfer encoding or a content length if (entity.isChunked() || entity.getContentLength() < 0) { if (ver.lessEquals(HttpVersion.HTTP_1_0)) { throw new ProtocolException( "Chunked transfer encoding not allowed for " + ver); } request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); } else { request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength())); } // Specify a content type if known if (entity.getContentType() != null && !request.containsHeader( HTTP.CONTENT_TYPE )) { request.addHeader(entity.getContentType()); } // Specify a content encoding if known if (entity.getContentEncoding() != null && !request.containsHeader( HTTP.CONTENT_ENCODING)) { request.addHeader(entity.getContentEncoding()); } } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/0040755 0000000 0000000 00000000000 12613456021 024344 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/TrustStrategy.java0100644 0000000 0000000 00000004671 12613456021 030060 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.ssl; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * A strategy to establish trustworthiness of certificates without consulting the trust manager * configured in the actual SSL context. This interface can be used to override the standard * JSSE certificate verification process. * * @since 4.4 */ public interface TrustStrategy { /** * Determines whether the certificate chain can be trusted without consulting the trust manager * configured in the actual SSL context. This method can be used to override the standard JSSE * certificate verification process. *

* Please note that, if this method returns {@code false}, the trust manager configured * in the actual SSL context can still clear the certificate as trusted. * * @param chain the peer certificate chain * @param authType the authentication type based on the client certificate * @return {@code true} if the certificate can be trusted without verification by * the trust manager, {@code false} otherwise. * @throws CertificateException thrown if the certificate is not trusted or invalid. */ boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException; } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/PrivateKeyDetails.java0100644 0000000 0000000 00000003622 12613456021 030600 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.ssl; import org.apache.http.util.Args; import java.security.cert.X509Certificate; import java.util.Arrays; /** * Private key details. * * @since 4.4 */ public final class PrivateKeyDetails { private final String type; private final X509Certificate[] certChain; public PrivateKeyDetails(final String type, final X509Certificate[] certChain) { super(); this.type = Args.notNull(type, "Private key type"); this.certChain = certChain; } public String getType() { return type; } public X509Certificate[] getCertChain() { return certChain; } @Override public String toString() { return type + ':' + Arrays.toString(certChain); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/SSLContexts.java0100644 0000000 0000000 00000006152 12613456021 027401 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.ssl; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import org.apache.http.annotation.Immutable; /** * {@link javax.net.ssl.SSLContext} factory methods. * * @since 4.4 */ @Immutable public class SSLContexts { /** * Creates default factory based on the standard JSSE trust material * ({@code cacerts} file in the security properties directory). System properties * are not taken into consideration. * * @return the default SSL socket factory */ public static SSLContext createDefault() throws SSLInitializationException { try { final SSLContext sslcontext = SSLContext.getInstance(SSLContextBuilder.TLS); sslcontext.init(null, null, null); return sslcontext; } catch (final NoSuchAlgorithmException ex) { throw new SSLInitializationException(ex.getMessage(), ex); } catch (final KeyManagementException ex) { throw new SSLInitializationException(ex.getMessage(), ex); } } /** * Creates default SSL context based on system properties. This method obtains * default SSL context by calling {@code SSLContext.getInstance("Default")}. * Please note that {@code Default} algorithm is supported as of Java 6. * This method will fall back onto {@link #createDefault()} when * {@code Default} algorithm is not available. * * @return default system SSL context */ public static SSLContext createSystemDefault() throws SSLInitializationException { try { return SSLContext.getDefault(); } catch (final NoSuchAlgorithmException ex) { return createDefault(); } } /** * Creates custom SSL context. * * @return default system SSL context */ public static SSLContextBuilder custom() { return SSLContextBuilder.create(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/package-info.java0100644 0000000 0000000 00000002446 12613456021 027536 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ /** * Utility classes for trust and key material management * and TLS/SSL context initialization. */ package org.apache.http.ssl; httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/SSLContextBuilder.java0100644 0000000 0000000 00000037504 12613456021 030532 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.ssl; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509TrustManager; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; /** * Builder for {@link javax.net.ssl.SSLContext} instances. *

* Please note: the default Oracle JSSE implementation of {@link SSLContext#init(KeyManager[], TrustManager[], SecureRandom)} * accepts multiple key and trust managers, however only only first matching type is ever used. * See for example: * * SSLContext.html#init * * * @since 4.4 */ @NotThreadSafe public class SSLContextBuilder { static final String TLS = "TLS"; private String protocol; private final Set keymanagers; private final Set trustmanagers; private SecureRandom secureRandom; public static SSLContextBuilder create() { return new SSLContextBuilder(); } public SSLContextBuilder() { super(); this.keymanagers = new LinkedHashSet(); this.trustmanagers = new LinkedHashSet(); } public SSLContextBuilder useProtocol(final String protocol) { this.protocol = protocol; return this; } public SSLContextBuilder setSecureRandom(final SecureRandom secureRandom) { this.secureRandom = secureRandom; return this; } public SSLContextBuilder loadTrustMaterial( final KeyStore truststore, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException { final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(truststore); final TrustManager[] tms = tmfactory.getTrustManagers(); if (tms != null) { if (trustStrategy != null) { for (int i = 0; i < tms.length; i++) { final TrustManager tm = tms[i]; if (tm instanceof X509TrustManager) { tms[i] = new TrustManagerDelegate( (X509TrustManager) tm, trustStrategy); } } } for (final TrustManager tm : tms) { this.trustmanagers.add(tm); } } return this; } public SSLContextBuilder loadTrustMaterial( final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException { return loadTrustMaterial(null, trustStrategy); } public SSLContextBuilder loadTrustMaterial( final File file, final char[] storePassword, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { Args.notNull(file, "Truststore file"); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); final FileInputStream instream = new FileInputStream(file); try { trustStore.load(instream, storePassword); } finally { instream.close(); } return loadTrustMaterial(trustStore, trustStrategy); } public SSLContextBuilder loadTrustMaterial( final File file, final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { return loadTrustMaterial(file, storePassword, null); } public SSLContextBuilder loadTrustMaterial( final File file) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { return loadTrustMaterial(file, null); } public SSLContextBuilder loadTrustMaterial( final URL url, final char[] storePassword, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { Args.notNull(url, "Truststore URL"); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); final InputStream instream = url.openStream(); try { trustStore.load(instream, storePassword); } finally { instream.close(); } return loadTrustMaterial(trustStore, trustStrategy); } public SSLContextBuilder loadTrustMaterial( final URL url, final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { return loadTrustMaterial(url, storePassword, null); } public SSLContextBuilder loadKeyMaterial( final KeyStore keystore, final char[] keyPassword, final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, keyPassword); final KeyManager[] kms = kmfactory.getKeyManagers(); if (kms != null) { if (aliasStrategy != null) { for (int i = 0; i < kms.length; i++) { final KeyManager km = kms[i]; if (km instanceof X509ExtendedKeyManager) { kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy); } } } for (final KeyManager km : kms) { keymanagers.add(km); } } return this; } public SSLContextBuilder loadKeyMaterial( final KeyStore keystore, final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { return loadKeyMaterial(keystore, keyPassword, null); } public SSLContextBuilder loadKeyMaterial( final File file, final char[] storePassword, final char[] keyPassword, final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException { Args.notNull(file, "Keystore file"); final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType()); final FileInputStream instream = new FileInputStream(file); try { identityStore.load(instream, storePassword); } finally { instream.close(); } return loadKeyMaterial(identityStore, keyPassword, aliasStrategy); } public SSLContextBuilder loadKeyMaterial( final File file, final char[] storePassword, final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException { return loadKeyMaterial(file, storePassword, keyPassword, null); } public SSLContextBuilder loadKeyMaterial( final URL url, final char[] storePassword, final char[] keyPassword, final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException { Args.notNull(url, "Keystore URL"); final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType()); final InputStream instream = url.openStream(); try { identityStore.load(instream, storePassword); } finally { instream.close(); } return loadKeyMaterial(identityStore, keyPassword, aliasStrategy); } public SSLContextBuilder loadKeyMaterial( final URL url, final char[] storePassword, final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException { return loadKeyMaterial(url, storePassword, keyPassword, null); } protected void initSSLContext( final SSLContext sslcontext, final Collection keyManagers, final Collection trustManagers, final SecureRandom secureRandom) throws KeyManagementException { sslcontext.init( !keyManagers.isEmpty() ? keyManagers.toArray(new KeyManager[keyManagers.size()]) : null, !trustManagers.isEmpty() ? trustManagers.toArray(new TrustManager[trustManagers.size()]) : null, secureRandom); } public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException { final SSLContext sslcontext = SSLContext.getInstance( this.protocol != null ? this.protocol : TLS); initSSLContext(sslcontext, keymanagers, trustmanagers, secureRandom); return sslcontext; } static class TrustManagerDelegate implements X509TrustManager { private final X509TrustManager trustManager; private final TrustStrategy trustStrategy; TrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) { super(); this.trustManager = trustManager; this.trustStrategy = trustStrategy; } @Override public void checkClientTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { this.trustManager.checkClientTrusted(chain, authType); } @Override public void checkServerTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { if (!this.trustStrategy.isTrusted(chain, authType)) { this.trustManager.checkServerTrusted(chain, authType); } } @Override public X509Certificate[] getAcceptedIssuers() { return this.trustManager.getAcceptedIssuers(); } } static class KeyManagerDelegate extends X509ExtendedKeyManager { private final X509ExtendedKeyManager keyManager; private final PrivateKeyStrategy aliasStrategy; KeyManagerDelegate(final X509ExtendedKeyManager keyManager, final PrivateKeyStrategy aliasStrategy) { super(); this.keyManager = keyManager; this.aliasStrategy = aliasStrategy; } @Override public String[] getClientAliases( final String keyType, final Principal[] issuers) { return this.keyManager.getClientAliases(keyType, issuers); } public Map getClientAliasMap( final String[] keyTypes, final Principal[] issuers) { final Map validAliases = new HashMap(); for (final String keyType: keyTypes) { final String[] aliases = this.keyManager.getClientAliases(keyType, issuers); if (aliases != null) { for (final String alias: aliases) { validAliases.put(alias, new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); } } } return validAliases; } public Map getServerAliasMap( final String keyType, final Principal[] issuers) { final Map validAliases = new HashMap(); final String[] aliases = this.keyManager.getServerAliases(keyType, issuers); if (aliases != null) { for (final String alias: aliases) { validAliases.put(alias, new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); } } return validAliases; } @Override public String chooseClientAlias( final String[] keyTypes, final Principal[] issuers, final Socket socket) { final Map validAliases = getClientAliasMap(keyTypes, issuers); return this.aliasStrategy.chooseAlias(validAliases, socket); } @Override public String[] getServerAliases( final String keyType, final Principal[] issuers) { return this.keyManager.getServerAliases(keyType, issuers); } @Override public String chooseServerAlias( final String keyType, final Principal[] issuers, final Socket socket) { final Map validAliases = getServerAliasMap(keyType, issuers); return this.aliasStrategy.chooseAlias(validAliases, socket); } @Override public X509Certificate[] getCertificateChain(final String alias) { return this.keyManager.getCertificateChain(alias); } @Override public PrivateKey getPrivateKey(final String alias) { return this.keyManager.getPrivateKey(alias); } @Override public String chooseEngineClientAlias( final String[] keyTypes, final Principal[] issuers, final SSLEngine sslEngine) { final Map validAliases = getClientAliasMap(keyTypes, issuers); return this.aliasStrategy.chooseAlias(validAliases, null); } @Override public String chooseEngineServerAlias( final String keyType, final Principal[] issuers, final SSLEngine sslEngine) { final Map validAliases = getServerAliasMap(keyType, issuers); return this.aliasStrategy.chooseAlias(validAliases, null); } } } ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/SSLInitializationException.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/SSLInitializationException.java0100644 0000000 0000000 00000002715 12613456021 032441 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.ssl; public class SSLInitializationException extends IllegalStateException { private static final long serialVersionUID = -8243587425648536702L; public SSLInitializationException(final String message, final Throwable cause) { super(message, cause); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/ssl/PrivateKeyStrategy.java0100644 0000000 0000000 00000003361 12613456021 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.ssl; import java.net.Socket; import java.util.Map; /** * A strategy allowing for a choice of an alias during SSL authentication. * * @since 4.4 */ public interface PrivateKeyStrategy { /** * Determines what key material to use for SSL authentication. * * @param aliases available private key material * @param socket socket used for the connection. Please note this parameter can be {@code null} * if key material is applicable to any socket. */ String chooseAlias(Map aliases, Socket socket); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/pool/0040755 0000000 0000000 00000000000 12613456021 024514 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/pool/RouteSpecificPool.java0100644 0000000 0000000 00000012504 12613456021 030754 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/pool/PoolEntryCallback.java0100644 0000000 0000000 00000002713 12613456021 030727 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/pool/PoolStats.java0100644 0000000 0000000 00000007165 12613456021 027315 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.Serializable; 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 implements Serializable { private static final long serialVersionUID = -2807686144795228544L; 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.4.4/httpcore/src/main/java/org/apache/http/pool/ConnFactory.java0100644 0000000 0000000 00000002772 12613456021 027611 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/pool/package-info.java0100644 0000000 0000000 00000002430 12613456021 027677 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/pool/PoolEntry.java0100644 0000000 0000000 00000013265 12613456021 027316 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 validityDeadline; @GuardedBy("this") private long updated; @GuardedBy("this") private long expiry; private volatile Object state; /** * Creates new {@code PoolEntry} instance. * * @param id unique identifier of the pool entry. May be {@code null}. * @param route route to the opposite endpoint. * @param conn the connection. * @param timeToLive maximum time to live. May be zero if the connection * does not have an expiry deadline. * @param tunit time unit. */ public PoolEntry(final String id, final T route, final C conn, final long timeToLive, final TimeUnit tunit) { super(); Args.notNull(route, "Route"); Args.notNull(conn, "Connection"); Args.notNull(tunit, "Time unit"); this.id = id; this.route = route; this.conn = conn; this.created = System.currentTimeMillis(); if (timeToLive > 0) { this.validityDeadline = this.created + tunit.toMillis(timeToLive); } else { this.validityDeadline = Long.MAX_VALUE; } this.expiry = this.validityDeadline; } /** * Creates new {@code PoolEntry} instance without an expiry deadline. * * @param id unique identifier of the pool entry. May be {@code null}. * @param route route to the opposite endpoint. * @param conn the connection. */ public PoolEntry(final String id, final T route, final C conn) { this(id, route, conn, 0, TimeUnit.MILLISECONDS); } public String getId() { return this.id; } public T getRoute() { return this.route; } public C getConnection() { return this.conn; } public long getCreated() { return this.created; } /** * @since 4.4 */ public long getValidityDeadline() { return this.validityDeadline; } /** * @deprecated use {@link #getValidityDeadline()} */ @Deprecated public long getValidUnit() { return this.validityDeadline; } public Object getState() { return this.state; } public void setState(final Object state) { this.state = state; } public synchronized long getUpdated() { return this.updated; } public synchronized long getExpiry() { return this.expiry; } public synchronized void updateExpiry(final long time, final TimeUnit tunit) { Args.notNull(tunit, "Time unit"); this.updated = System.currentTimeMillis(); final long newExpiry; if (time > 0) { newExpiry = this.updated + tunit.toMillis(time); } else { newExpiry = Long.MAX_VALUE; } this.expiry = Math.min(newExpiry, this.validityDeadline); } public synchronized boolean isExpired(final long now) { return now >= this.expiry; } /** * Invalidates the pool entry and closes the pooled connection associated * with it. */ public abstract void close(); /** * Returns {@code true} if the pool entry has been invalidated. */ public abstract boolean isClosed(); @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append("[id:"); buffer.append(this.id); buffer.append("][route:"); buffer.append(this.route); buffer.append("][state:"); buffer.append(this.state); buffer.append("]"); return buffer.toString(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/pool/ConnPoolControl.java0100644 0000000 0000000 00000003444 12613456021 030451 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/pool/AbstractConnPool.java0100644 0000000 0000000 00000046151 12613456021 030576 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; private volatile int validateAfterInactivity; public AbstractConnPool( final ConnFactory connFactory, final int defaultMaxPerRoute, final int maxTotal) { super(); this.connFactory = Args.notNull(connFactory, "Connection factory"); this.defaultMaxPerRoute = Args.positive(defaultMaxPerRoute, "Max per route value"); this.maxTotal = Args.positive(maxTotal, "Max total value"); this.lock = new ReentrantLock(); this.routeToPool = new HashMap>(); this.leased = new HashSet(); this.available = new LinkedList(); this.pending = new LinkedList>(); this.maxPerRoute = new HashMap(); } /** * Creates a new entry for the given connection with the given route. */ protected abstract E createEntry(T route, C conn); /** * @since 4.3 */ protected void onLease(final E entry) { } /** * @since 4.3 */ protected void onRelease(final E entry) { } /** * @since 4.4 */ protected void onReuse(final E entry) { } /** * @since 4.4 */ protected boolean validate(final E entry) { return true; } public boolean isShutdown() { return this.isShutDown; } /** * Shuts down the pool. */ public void shutdown() throws IOException { if (this.isShutDown) { return ; } this.isShutDown = true; this.lock.lock(); try { for (final E entry: this.available) { entry.close(); } for (final E entry: this.leased) { entry.close(); } for (final RouteSpecificPool pool: this.routeToPool.values()) { pool.shutdown(); } this.routeToPool.clear(); this.leased.clear(); this.available.clear(); } finally { this.lock.unlock(); } } private RouteSpecificPool getPool(final T route) { RouteSpecificPool pool = this.routeToPool.get(route); if (pool == null) { pool = new RouteSpecificPool(route) { @Override protected E createEntry(final C conn) { return AbstractConnPool.this.createEntry(route, conn); } }; this.routeToPool.put(route, pool); } return pool; } /** * {@inheritDoc} *

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

* Please note that this class does not maintain its own pool of execution * {@link Thread}s. Therefore, one must call {@link Future#get()} * or {@link Future#get(long, TimeUnit)} method on the {@link Future} * returned by this method in order for the lease operation to complete. * * @param route route of the connection. * @param state arbitrary object that represents a particular state * (usually a security principal or a unique token identifying * the user whose credentials have been used while establishing the connection). * May be {@code null}. * @return future for a leased pool entry. */ public Future lease(final T route, final Object state) { return lease(route, state, null); } private E getPoolEntryBlocking( final T route, final Object state, final long timeout, final TimeUnit tunit, final PoolEntryFuture future) throws IOException, InterruptedException, TimeoutException { Date deadline = null; if (timeout > 0) { deadline = new Date (System.currentTimeMillis() + tunit.toMillis(timeout)); } this.lock.lock(); try { final RouteSpecificPool pool = getPool(route); E entry = null; while (entry == null) { Asserts.check(!this.isShutDown, "Connection pool shut down"); for (;;) { entry = pool.getFree(state); if (entry == null) { break; } if (entry.isExpired(System.currentTimeMillis())) { entry.close(); } else if (this.validateAfterInactivity > 0) { if (entry.getUpdated() + this.validateAfterInactivity <= System.currentTimeMillis()) { if (!validate(entry)) { entry.close(); } } } if (entry.isClosed()) { this.available.remove(entry); pool.free(entry, false); } else { break; } } if (entry != null) { this.available.remove(entry); this.leased.add(entry); onReuse(entry); return entry; } // New connection is needed final int maxPerRoute = getMax(route); // Shrink the pool prior to allocating a new connection final int excess = Math.max(0, pool.getAllocatedCount() + 1 - maxPerRoute); if (excess > 0) { for (int i = 0; i < excess; i++) { final E lastUsed = pool.getLastUsed(); if (lastUsed == null) { break; } lastUsed.close(); this.available.remove(lastUsed); pool.remove(lastUsed); } } if (pool.getAllocatedCount() < maxPerRoute) { final int totalUsed = this.leased.size(); final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0); if (freeCapacity > 0) { final int totalAvailable = this.available.size(); if (totalAvailable > freeCapacity - 1) { if (!this.available.isEmpty()) { final E lastUsed = this.available.removeLast(); lastUsed.close(); final RouteSpecificPool otherpool = getPool(lastUsed.getRoute()); otherpool.remove(lastUsed); } } final C conn = this.connFactory.create(route); entry = pool.add(conn); this.leased.add(entry); return entry; } } boolean success = false; try { pool.queue(future); this.pending.add(future); success = future.await(deadline); } finally { // In case of 'success', we were woken up by the // connection pool and should now have a connection // waiting for us, or else we're shutting down. // Just continue in the loop, both cases are checked. pool.unqueue(future); this.pending.remove(future); } // check for spurious wakeup vs. timeout if (!success && (deadline != null) && (deadline.getTime() <= System.currentTimeMillis())) { break; } } throw new TimeoutException("Timeout waiting for connection"); } finally { this.lock.unlock(); } } @Override public void release(final E entry, final boolean reusable) { this.lock.lock(); try { if (this.leased.remove(entry)) { final RouteSpecificPool pool = getPool(entry.getRoute()); pool.free(entry, reusable); if (reusable && !this.isShutDown) { this.available.addFirst(entry); onRelease(entry); } else { entry.close(); } PoolEntryFuture future = pool.nextPending(); if (future != null) { this.pending.remove(future); } else { future = this.pending.poll(); } if (future != null) { future.wakeup(); } } } finally { this.lock.unlock(); } } private int getMax(final T route) { final Integer v = this.maxPerRoute.get(route); if (v != null) { return v.intValue(); } else { return this.defaultMaxPerRoute; } } @Override public void setMaxTotal(final int max) { Args.positive(max, "Max value"); this.lock.lock(); try { this.maxTotal = max; } finally { this.lock.unlock(); } } @Override public int getMaxTotal() { this.lock.lock(); try { return this.maxTotal; } finally { this.lock.unlock(); } } @Override public void setDefaultMaxPerRoute(final int max) { Args.positive(max, "Max per route value"); this.lock.lock(); try { this.defaultMaxPerRoute = max; } finally { this.lock.unlock(); } } @Override public int getDefaultMaxPerRoute() { this.lock.lock(); try { return this.defaultMaxPerRoute; } finally { this.lock.unlock(); } } @Override public void setMaxPerRoute(final T route, final int max) { Args.notNull(route, "Route"); Args.positive(max, "Max per route value"); this.lock.lock(); try { this.maxPerRoute.put(route, Integer.valueOf(max)); } finally { this.lock.unlock(); } } @Override public int getMaxPerRoute(final T route) { Args.notNull(route, "Route"); this.lock.lock(); try { return getMax(route); } finally { this.lock.unlock(); } } @Override public PoolStats getTotalStats() { this.lock.lock(); try { return new PoolStats( this.leased.size(), this.pending.size(), this.available.size(), this.maxTotal); } finally { this.lock.unlock(); } } @Override public PoolStats getStats(final T route) { Args.notNull(route, "Route"); this.lock.lock(); try { final RouteSpecificPool pool = getPool(route); return new PoolStats( pool.getLeasedCount(), pool.getPendingCount(), pool.getAvailableCount(), getMax(route)); } finally { this.lock.unlock(); } } /** * Returns snapshot of all knows routes * @return the set of routes * * @since 4.4 */ public Set getRoutes() { this.lock.lock(); try { return new HashSet(routeToPool.keySet()); } finally { this.lock.unlock(); } } /** * Enumerates all available connections. * * @since 4.3 */ protected void enumAvailable(final PoolEntryCallback callback) { this.lock.lock(); try { final Iterator it = this.available.iterator(); while (it.hasNext()) { final E entry = it.next(); callback.process(entry); if (entry.isClosed()) { final RouteSpecificPool pool = getPool(entry.getRoute()); pool.remove(entry); it.remove(); } } purgePoolMap(); } finally { this.lock.unlock(); } } /** * Enumerates all leased connections. * * @since 4.3 */ protected void enumLeased(final PoolEntryCallback callback) { this.lock.lock(); try { final Iterator it = this.leased.iterator(); while (it.hasNext()) { final E entry = it.next(); callback.process(entry); } } finally { this.lock.unlock(); } } private void purgePoolMap() { final Iterator>> it = this.routeToPool.entrySet().iterator(); while (it.hasNext()) { final Map.Entry> entry = it.next(); final RouteSpecificPool pool = entry.getValue(); if (pool.getPendingCount() + pool.getAllocatedCount() == 0) { it.remove(); } } } /** * Closes connections that have been idle longer than the given period * of time and evicts them from the pool. * * @param idletime maximum idle time. * @param tunit time unit. */ public void closeIdle(final long idletime, final TimeUnit tunit) { Args.notNull(tunit, "Time unit"); long time = tunit.toMillis(idletime); if (time < 0) { time = 0; } final long deadline = System.currentTimeMillis() - time; enumAvailable(new PoolEntryCallback() { @Override public void process(final PoolEntry entry) { if (entry.getUpdated() <= deadline) { entry.close(); } } }); } /** * Closes expired connections and evicts them from the pool. */ public void closeExpired() { final long now = System.currentTimeMillis(); enumAvailable(new PoolEntryCallback() { @Override public void process(final PoolEntry entry) { if (entry.isExpired(now)) { entry.close(); } } }); } /** * @return the number of milliseconds * @since 4.4 */ public int getValidateAfterInactivity() { return this.validateAfterInactivity; } /** * @param ms the number of milliseconds * @since 4.4 */ public void setValidateAfterInactivity(final int ms) { this.validateAfterInactivity = ms; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append("[leased: "); buffer.append(this.leased); buffer.append("][available: "); buffer.append(this.available); buffer.append("][pending: "); buffer.append(this.pending); buffer.append("]"); return buffer.toString(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/pool/PoolEntryFuture.java0100644 0000000 0000000 00000011535 12613456021 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.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; } @Override public boolean cancel(final boolean mayInterruptIfRunning) { this.lock.lock(); try { if (this.completed) { return false; } this.completed = true; this.cancelled = true; if (this.callback != null) { this.callback.cancelled(); } this.condition.signalAll(); return true; } finally { this.lock.unlock(); } } @Override public boolean isCancelled() { return this.cancelled; } @Override public boolean isDone() { return this.completed; } @Override public T get() throws InterruptedException, ExecutionException { try { return get(0, TimeUnit.MILLISECONDS); } catch (final TimeoutException ex) { throw new ExecutionException(ex); } } @Override public T get( final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Args.notNull(unit, "Time unit"); this.lock.lock(); try { if (this.completed) { return this.result; } this.result = getPoolEntry(timeout, unit); this.completed = true; if (this.callback != null) { this.callback.completed(this.result); } return result; } catch (final IOException ex) { this.completed = true; this.result = null; if (this.callback != null) { this.callback.failed(ex); } throw new ExecutionException(ex); } finally { this.lock.unlock(); } } protected abstract T getPoolEntry( long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException; public boolean await(final Date deadline) throws InterruptedException { this.lock.lock(); try { if (this.cancelled) { throw new InterruptedException("Operation interrupted"); } final boolean success; if (deadline != null) { success = this.condition.awaitUntil(deadline); } else { this.condition.await(); success = true; } if (this.cancelled) { throw new InterruptedException("Operation interrupted"); } return success; } finally { this.lock.unlock(); } } public void wakeup() { this.lock.lock(); try { this.condition.signalAll(); } finally { this.lock.unlock(); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/pool/ConnPool.java0100644 0000000 0000000 00000005015 12613456021 027104 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; /** * {@code ConnPool} represents a shared pool connections can be leased from * and released back to. * * @param the route type that represents the opposite endpoint of a pooled * connection. * @param the type of the pool entry containing a pooled connection. * @since 4.2 */ public interface ConnPool { /** * Attempts to lease a connection for the given route and with the given * state from the pool. * * @param route route of the connection. * @param state arbitrary object that represents a particular state * (usually a security principal or a unique token identifying * the user whose credentials have been used while establishing the connection). * May be {@code null}. * @param callback operation completion callback. * * @return future for a leased pool entry. */ Future lease(final T route, final Object state, final FutureCallback callback); /** * Releases the pool entry back to the pool. * * @param entry pool entry leased from the pool * @param reusable flag indicating whether or not the released connection * is in a consistent state and is safe for further use. */ void release(E entry, boolean reusable); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/config/0040755 0000000 0000000 00000000000 12613456021 025010 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/config/SocketConfig.java0100644 0000000 0000000 00000021574 12613456021 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; private final int sndBufSize; private final int rcvBufSize; private int backlogSize; SocketConfig( final int soTimeout, final boolean soReuseAddress, final int soLinger, final boolean soKeepAlive, final boolean tcpNoDelay, final int sndBufSize, final int rcvBufSize, final int backlogSize) { super(); this.soTimeout = soTimeout; this.soReuseAddress = soReuseAddress; this.soLinger = soLinger; this.soKeepAlive = soKeepAlive; this.tcpNoDelay = tcpNoDelay; this.sndBufSize = sndBufSize; this.rcvBufSize = rcvBufSize; this.backlogSize = backlogSize; } /** * Determines the default socket timeout value for non-blocking I/O operations. *

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

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

* Default: {@code false} *

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

* Default: {@code -1} *

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

* Default: {@code -1} *

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

* Default: {@code false} *

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

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

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

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

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

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

* @return the maximum queue length for incoming connection indications * @since 4.4 */ public int getBacklogSize() { return backlogSize; } @Override protected SocketConfig clone() throws CloneNotSupportedException { return (SocketConfig) super.clone(); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[soTimeout=").append(this.soTimeout) .append(", soReuseAddress=").append(this.soReuseAddress) .append(", soLinger=").append(this.soLinger) .append(", soKeepAlive=").append(this.soKeepAlive) .append(", tcpNoDelay=").append(this.tcpNoDelay) .append(", sndBufSize=").append(this.sndBufSize) .append(", rcvBufSize=").append(this.rcvBufSize) .append(", backlogSize=").append(this.backlogSize) .append("]"); return builder.toString(); } public static SocketConfig.Builder custom() { return new Builder(); } public static SocketConfig.Builder copy(final SocketConfig config) { Args.notNull(config, "Socket config"); return new Builder() .setSoTimeout(config.getSoTimeout()) .setSoReuseAddress(config.isSoReuseAddress()) .setSoLinger(config.getSoLinger()) .setSoKeepAlive(config.isSoKeepAlive()) .setTcpNoDelay(config.isTcpNoDelay()) .setSndBufSize(config.getSndBufSize()) .setRcvBufSize(config.getRcvBufSize()) .setBacklogSize(config.getBacklogSize()); } public static class Builder { private int soTimeout; private boolean soReuseAddress; private int soLinger; private boolean soKeepAlive; private boolean tcpNoDelay; private int sndBufSize; private int rcvBufSize; private int backlogSize; Builder() { this.soLinger = -1; this.tcpNoDelay = true; } public Builder setSoTimeout(final int soTimeout) { this.soTimeout = soTimeout; return this; } public Builder setSoReuseAddress(final boolean soReuseAddress) { this.soReuseAddress = soReuseAddress; return this; } public Builder setSoLinger(final int soLinger) { this.soLinger = soLinger; return this; } public Builder setSoKeepAlive(final boolean soKeepAlive) { this.soKeepAlive = soKeepAlive; return this; } public Builder setTcpNoDelay(final boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; return this; } /** * @since 4.4 */ public Builder setSndBufSize(final int sndBufSize) { this.sndBufSize = sndBufSize; return this; } /** * @since 4.4 */ public Builder setRcvBufSize(final int rcvBufSize) { this.rcvBufSize = rcvBufSize; return this; } /** * @since 4.4 */ public Builder setBacklogSize(final int backlogSize) { this.backlogSize = backlogSize; return this; } public SocketConfig build() { return new SocketConfig(soTimeout, soReuseAddress, soLinger, soKeepAlive, tcpNoDelay, sndBufSize, rcvBufSize, backlogSize); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/config/package-info.java0100644 0000000 0000000 00000002345 12613456021 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 * . * */ /** * Core configuration APIs. */ package org.apache.http.config; httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/config/Lookup.java0100644 0000000 0000000 00000002501 12613456021 027117 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/config/ConnectionConfig.java0100644 0000000 0000000 00000014772 12613456021 031110 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/config/RegistryBuilder.java0100644 0000000 0000000 00000004115 12613456021 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.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.ROOT), item); return this; } public Registry build() { return new Registry(items); } @Override public String toString() { return items.toString(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/config/Registry.java0100644 0000000 0000000 00000003616 12613456021 027466 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override public I lookup(final String key) { if (key == null) { return null; } return map.get(key.toLowerCase(Locale.ROOT)); } @Override public String toString() { return map.toString(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/config/MessageConstraints.java0100644 0000000 0000000 00000007226 12613456021 031473 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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. *

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

* * @since 4.3 */ public class MessageConstraints implements Cloneable { public static final MessageConstraints DEFAULT = new Builder().build(); private final int maxLineLength; private final int maxHeaderCount; MessageConstraints(final int maxLineLength, final int maxHeaderCount) { super(); this.maxLineLength = maxLineLength; this.maxHeaderCount = maxHeaderCount; } public int getMaxLineLength() { return maxLineLength; } public int getMaxHeaderCount() { return maxHeaderCount; } @Override protected MessageConstraints clone() throws CloneNotSupportedException { return (MessageConstraints) super.clone(); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[maxLineLength=").append(maxLineLength) .append(", maxHeaderCount=").append(maxHeaderCount) .append("]"); return builder.toString(); } public static MessageConstraints lineLen(final int max) { return new MessageConstraints(Args.notNegative(max, "Max line length"), -1); } public static MessageConstraints.Builder custom() { return new Builder(); } public static MessageConstraints.Builder copy(final MessageConstraints config) { Args.notNull(config, "Message constraints"); return new Builder() .setMaxHeaderCount(config.getMaxHeaderCount()) .setMaxLineLength(config.getMaxLineLength()); } public static class Builder { private int maxLineLength; private int maxHeaderCount; Builder() { this.maxLineLength = -1; this.maxHeaderCount = -1; } public Builder setMaxLineLength(final int maxLineLength) { this.maxLineLength = maxLineLength; return this; } public Builder setMaxHeaderCount(final int maxHeaderCount) { this.maxHeaderCount = maxHeaderCount; return this; } public MessageConstraints build() { return new MessageConstraints(maxLineLength, maxHeaderCount); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/0040755 0000000 0000000 00000000000 12613456022 024521 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/Asserts.java0100644 0000000 0000000 00000004570 12613456022 027013 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 check(final boolean expression, final String message, final Object arg) { if (!expression) { throw new IllegalStateException(String.format(message, arg)); } } public static void notNull(final Object object, final String name) { if (object == null) { throw new IllegalStateException(name + " is null"); } } public static void notEmpty(final CharSequence s, final String name) { if (TextUtils.isEmpty(s)) { throw new IllegalStateException(name + " is empty"); } } public static void notBlank(final CharSequence s, final String name) { if (TextUtils.isBlank(s)) { throw new IllegalStateException(name + " is blank"); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/package-info.java0100644 0000000 0000000 00000002340 12613456022 027704 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/util/CharsetUtils.java0100644 0000000 0000000 00000003705 12613456022 030000 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/util/Args.java0100644 0000000 0000000 00000010526 12613456022 026261 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 void check(final boolean expression, final String message, final Object arg) { if (!expression) { throw new IllegalArgumentException(String.format(message, arg)); } } public static T notNull(final T argument, final String name) { if (argument == null) { throw new IllegalArgumentException(name + " may not be null"); } return argument; } public static T notEmpty(final T argument, final String name) { if (argument == null) { throw new IllegalArgumentException(name + " may not be null"); } if (TextUtils.isEmpty(argument)) { throw new IllegalArgumentException(name + " may not be empty"); } return argument; } public static T notBlank(final T argument, final String name) { if (argument == null) { throw new IllegalArgumentException(name + " may not be null"); } if (TextUtils.isBlank(argument)) { throw new IllegalArgumentException(name + " may not be blank"); } return argument; } public static T containsNoBlanks(final T argument, final String name) { if (argument == null) { throw new IllegalArgumentException(name + " may not be null"); } if (TextUtils.containsBlanks(argument)) { throw new IllegalArgumentException(name + " may not contain blanks"); } return argument; } public static > T notEmpty(final T argument, final String name) { if (argument == null) { throw new IllegalArgumentException(name + " may not be null"); } if (argument.isEmpty()) { throw new IllegalArgumentException(name + " may not be empty"); } return argument; } public static int positive(final int n, final String name) { if (n <= 0) { throw new IllegalArgumentException(name + " may not be negative or zero"); } return n; } public static long positive(final long n, final String name) { if (n <= 0) { throw new IllegalArgumentException(name + " may not be negative or zero"); } return n; } public static int notNegative(final int n, final String name) { if (n < 0) { throw new IllegalArgumentException(name + " may not be negative"); } return n; } public static long notNegative(final long n, final String name) { if (n < 0) { throw new IllegalArgumentException(name + " may not be negative"); } return n; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/EncodingUtils.java0100644 0000000 0000000 00000011473 12613456022 030136 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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"); return data.getBytes(Consts.ASCII); } /** * Converts the byte array of ASCII characters to a string. This method is * to be used when decoding content of HTTP elements (such as response * headers) * * @param data the byte array to be encoded * @param offset the index of the first byte to encode * @param length the number of bytes to encode * @return The string representation of the byte array */ public static String getAsciiString(final byte[] data, final int offset, final int length) { Args.notNull(data, "Input"); return new String(data, offset, length, Consts.ASCII); } /** * Converts the byte array of ASCII characters to a string. This method is * to be used when decoding content of HTTP elements (such as response * headers) * * @param data the byte array to be encoded * @return The string representation of the byte array */ public static String getAsciiString(final byte[] data) { Args.notNull(data, "Input"); return getAsciiString(data, 0, data.length); } /** * This class should not be instantiated. */ private EncodingUtils() { } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/TextUtils.java0100644 0000000 0000000 00000004304 12613456022 027327 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 { /** * Returns true if the parameter is null or of zero length */ public static boolean isEmpty(final CharSequence s) { if (s == null) { return true; } return s.length() == 0; } /** * Returns true if the parameter is null or contains only whitespace */ public static boolean isBlank(final CharSequence s) { if (s == null) { return true; } for (int i = 0; i < s.length(); i++) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } /** * @since 4.4 */ public static boolean containsBlanks(final CharSequence s) { if (s == null) { return false; } for (int i = 0; i < s.length(); i++) { if (Character.isWhitespace(s.charAt(i))) { return true; } } return false; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/VersionInfo.java0100644 0000000 0000000 00000026560 12613456022 027633 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} * @param release the release, or {@code null} * @param time the build time, or {@code null} * @param clsldr the class loader, or {@code null} */ protected VersionInfo(final String pckg, final String module, final String release, final String time, final String clsldr) { Args.notNull(pckg, "Package identifier"); infoPackage = pckg; infoModule = (module != null) ? module : UNAVAILABLE; infoRelease = (release != null) ? release : UNAVAILABLE; infoTimestamp = (time != null) ? time : UNAVAILABLE; infoClassloader = (clsldr != null) ? clsldr : UNAVAILABLE; } /** * Obtains the package name. * The package name identifies the module or informal unit. * * @return the package name, never {@code null} */ public final String getPackage() { return infoPackage; } /** * Obtains the name of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the module name, never {@code null} */ public final String getModule() { return infoModule; } /** * Obtains the release of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the release version, never {@code null} */ public final String getRelease() { return infoRelease; } /** * Obtains the timestamp of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the timestamp, never {@code null} */ public final String getTimestamp() { return infoTimestamp; } /** * Obtains the classloader used to read the version information. * This is just the {@code toString} output of the classloader, * since the version information should not keep a reference to * the classloader itself. That could prevent garbage collection. * * @return the classloader description, never {@code null} */ public final String getClassloader() { return infoClassloader; } /** * Provides the version information in human-readable format. * * @return a string holding this version information */ @Override public String toString() { final StringBuilder sb = new StringBuilder (20 + infoPackage.length() + infoModule.length() + infoRelease.length() + infoTimestamp.length() + infoClassloader.length()); sb.append("VersionInfo(") .append(infoPackage).append(':').append(infoModule); // If version info is missing, a single "UNAVAILABLE" for the module // is sufficient. Everything else just clutters the output. if (!UNAVAILABLE.equals(infoRelease)) { sb.append(':').append(infoRelease); } if (!UNAVAILABLE.equals(infoTimestamp)) { sb.append(':').append(infoTimestamp); } sb.append(')'); if (!UNAVAILABLE.equals(infoClassloader)) { sb.append('@').append(infoClassloader); } return sb.toString(); } /** * Loads version information for a list of packages. * * @param pckgs the packages for which to load version info * @param clsldr the classloader to load from, or * {@code null} for the thread context classloader * * @return the version information for all packages found, * never {@code null} */ public static VersionInfo[] loadVersionInfo(final String[] pckgs, final ClassLoader clsldr) { Args.notNull(pckgs, "Package identifier array"); final List vil = new ArrayList(pckgs.length); for (final String pckg : pckgs) { final VersionInfo vi = loadVersionInfo(pckg, clsldr); if (vi != null) { vil.add(vi); } } return vil.toArray(new VersionInfo[vil.size()]); } /** * Loads version information for a package. * * @param pckg the package for which to load version information, * for example "org.apache.http". * The package name should NOT end with a dot. * @param clsldr the classloader to load from, or * {@code null} for the thread context classloader * * @return the version information for the argument package, or * {@code null} if not available */ public static VersionInfo loadVersionInfo(final String pckg, final ClassLoader clsldr) { Args.notNull(pckg, "Package identifier"); final ClassLoader cl = clsldr != null ? clsldr : Thread.currentThread().getContextClassLoader(); Properties vip = null; // version info properties, if available try { // 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 {@code null} * * @return the version information */ protected static VersionInfo fromMap(final String pckg, final Map info, final ClassLoader clsldr) { Args.notNull(pckg, "Package identifier"); String module = null; String release = null; String timestamp = null; if (info != null) { module = (String) info.get(PROPERTY_MODULE); if ((module != null) && (module.length() < 1)) { module = null; } release = (String) info.get(PROPERTY_RELEASE); if ((release != null) && ((release.length() < 1) || (release.equals("${pom.version}")))) { release = null; } timestamp = (String) info.get(PROPERTY_TIMESTAMP); if ((timestamp != null) && ((timestamp.length() < 1) || (timestamp.equals("${mvn.timestamp}"))) ) { timestamp = null; } } // if info String clsldrstr = null; if (clsldr != null) { clsldrstr = clsldr.toString(); } return new VersionInfo(pckg, module, release, timestamp, clsldrstr); } /** * Sets the user agent to {@code "/ (Java/)"}. *

* For example: *

"Apache-HttpClient/4.3 (Java/1.6.0_35)"
* * @param name the component name, like "Apache-HttpClient". * @param pkg * the package for which to load version information, for example "org.apache.http". The package name * should NOT end with a dot. * @param cls * the class' class loader to load from, or {@code null} for the thread context class loader * @since 4.3 */ public static String getUserAgent(final String name, final String pkg, final Class cls) { // determine the release version from packaged version info final VersionInfo vi = VersionInfo.loadVersionInfo(pkg, cls.getClassLoader()); final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; final String javaVersion = System.getProperty("java.version"); return String.format("%s/%s (Java/%s)", name, release, javaVersion); } } // class VersionInfo httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/NetUtils.java0100644 0000000 0000000 00000003741 12613456022 027135 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/util/EntityUtils.java0100644 0000000 0000000 00000026047 12613456022 027667 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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, * or if the entity provided charset is invalid or not available. * @return the entity content as a String. May be null if * {@link HttpEntity#getContent()} is null. * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE * @throws IOException if an error occurs reading the input stream * @throws UnsupportedCharsetException Thrown when the named entity's charset is not available in * this instance of the Java virtual machine and no defaultCharset is provided. */ public static String toString( final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException { Args.notNull(entity, "Entity"); final InputStream instream = entity.getContent(); if (instream == null) { return null; } try { Args.check(entity.getContentLength() <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory"); int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } Charset charset = null; try { final ContentType contentType = ContentType.get(entity); if (contentType != null) { charset = contentType.getCharset(); } } catch (final UnsupportedCharsetException ex) { if (defaultCharset == null) { throw new UnsupportedEncodingException(ex.getMessage()); } } if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } final Reader reader = new InputStreamReader(instream, charset); final CharArrayBuffer buffer = new CharArrayBuffer(i); final char[] tmp = new char[1024]; int l; while((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } } /** * Get the entity content as a String, using the provided default character set * if none is found in the entity. * If defaultCharset is null, the default "ISO-8859-1" is used. * * @param entity must not be null * @param defaultCharset character set to be applied if none found in the entity * @return the entity content as a String. May be null if * {@link HttpEntity#getContent()} is null. * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE * @throws IOException if an error occurs reading the input stream * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public static String toString( final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { return toString(entity, defaultCharset != null ? Charset.forName(defaultCharset) : null); } /** * Read the contents of an entity and return it as a String. * The content is converted using the character set from the entity (if any), * failing that, "ISO-8859-1" is used. * * @param entity the entity to convert to a string; must not be null * @return String containing the content. * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE * @throws IOException if an error occurs reading the input stream * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public static String toString(final HttpEntity entity) throws IOException, ParseException { return toString(entity, (Charset)null); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/CharArrayBuffer.java0100644 0000000 0000000 00000042147 12613456022 030377 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 java.nio.CharBuffer; 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 CharSequence, Serializable { private static final long serialVersionUID = -6208952725094867135L; private char[] buffer; private int len; /** * Creates an instance of {@link CharArrayBuffer} with the given initial * capacity. * * @param capacity the capacity */ public CharArrayBuffer(final int capacity) { super(); Args.notNegative(capacity, "Buffer capacity"); this.buffer = new char[capacity]; } private void expand(final int newlen) { final char newbuffer[] = new char[Math.max(this.buffer.length << 1, newlen)]; System.arraycopy(this.buffer, 0, newbuffer, 0, this.len); this.buffer = newbuffer; } /** * Appends {@code len} chars to this buffer from the given source * array starting at index {@code off}. The capacity of the buffer * is increased, if necessary, to accommodate all {@code len} chars. * * @param b the chars to be appended. * @param off the index of the first char to append. * @param len the number of chars to append. * @throws IndexOutOfBoundsException if {@code off} is out of * range, {@code len} is negative, or * {@code off} + {@code len} is out of range. */ public void append(final char[] b, final int off, final int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } final int newlen = this.len + len; if (newlen > this.buffer.length) { expand(newlen); } System.arraycopy(b, off, this.buffer, this.len, len); this.len = newlen; } /** * Appends chars of the given string to this buffer. The capacity of the * buffer is increased, if necessary, to accommodate all chars. * * @param str the string. */ public void append(final String str) { final String s = str != null ? str : "null"; final int strlen = s.length(); final int newlen = this.len + strlen; if (newlen > this.buffer.length) { expand(newlen); } s.getChars(0, strlen, this.buffer, this.len); this.len = newlen; } /** * Appends {@code len} chars to this buffer from the given source * buffer starting at index {@code off}. The capacity of the * destination buffer is increased, if necessary, to accommodate all * {@code len} chars. * * @param b the source buffer to be appended. * @param off the index of the first char to append. * @param len the number of chars to append. * @throws IndexOutOfBoundsException if {@code off} is out of * range, {@code len} is negative, or * {@code off} + {@code len} is out of range. */ public void append(final CharArrayBuffer b, final int off, final int len) { if (b == null) { return; } append(b.buffer, off, len); } /** * Appends all chars to this buffer from the given source buffer starting * at index {@code 0}. The capacity of the destination buffer is * increased, if necessary, to accommodate all {@link #length()} chars. * * @param b the source buffer to be appended. */ public void append(final CharArrayBuffer b) { if (b == null) { return; } append(b.buffer,0, b.len); } /** * Appends {@code ch} char to this buffer. The capacity of the buffer * is increased, if necessary, to accommodate the additional char. * * @param ch the char to be appended. */ public void append(final char ch) { final int newlen = this.len + 1; if (newlen > this.buffer.length) { expand(newlen); } this.buffer[this.len] = ch; this.len = newlen; } /** * Appends {@code len} bytes to this buffer from the given source * array starting at index {@code off}. The capacity of the buffer * is increased, if necessary, to accommodate all {@code len} bytes. *

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

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

* There is no restriction on the value of {@code beginIndex} and * {@code endIndex}. If {@code beginIndex} is negative, * it has the same effect as if it were zero. If {@code endIndex} is * greater than {@link #length()}, it has the same effect as if it were * {@link #length()}. If the {@code beginIndex} is greater than * the {@code endIndex}, {@code -1} is returned. * * @param ch the char to search for. * @param from the index to start the search from. * @param to the index to finish the search at. * @return the index of the first occurrence of the character in the buffer * within the given bounds, or {@code -1} if the character does * not occur. */ public int indexOf(final int ch, final int from, final int to) { int beginIndex = from; if (beginIndex < 0) { beginIndex = 0; } int endIndex = to; if (endIndex > this.len) { endIndex = this.len; } if (beginIndex > endIndex) { return -1; } for (int i = beginIndex; i < endIndex; i++) { if (this.buffer[i] == ch) { return i; } } return -1; } /** * Returns the index within this buffer of the first occurrence of the * specified character, starting the search at {@code 0} and finishing * at {@link #length()}. If no such character occurs in this buffer within * those bounds, {@code -1} is returned. * * @param ch the char to search for. * @return the index of the first occurrence of the character in the * buffer, or {@code -1} if the character does not occur. */ public int indexOf(final int ch) { return indexOf(ch, 0, this.len); } /** * Returns a substring of this buffer. The substring begins at the specified * {@code beginIndex} and extends to the character at index * {@code endIndex - 1}. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception StringIndexOutOfBoundsException if the * {@code beginIndex} is negative, or * {@code endIndex} is larger than the length of this * buffer, or {@code beginIndex} is larger than * {@code endIndex}. */ public String substring(final int beginIndex, final int endIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("Negative beginIndex: " + beginIndex); } if (endIndex > this.len) { throw new IndexOutOfBoundsException("endIndex: " + endIndex + " > length: " + this.len); } if (beginIndex > endIndex) { throw new IndexOutOfBoundsException("beginIndex: " + beginIndex + " > endIndex: " + endIndex); } return new String(this.buffer, beginIndex, endIndex - beginIndex); } /** * Returns a substring of this buffer with leading and trailing whitespace * omitted. The substring begins with the first non-whitespace character * from {@code beginIndex} and extends to the last * non-whitespace character with the index lesser than * {@code endIndex}. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * {@code beginIndex} is negative, or * {@code endIndex} is larger than the length of this * buffer, or {@code beginIndex} is larger than * {@code endIndex}. */ public String substringTrimmed(final int beginIndex, final int endIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("Negative beginIndex: " + beginIndex); } if (endIndex > this.len) { throw new IndexOutOfBoundsException("endIndex: " + endIndex + " > length: " + this.len); } if (beginIndex > endIndex) { throw new IndexOutOfBoundsException("beginIndex: " + beginIndex + " > endIndex: " + endIndex); } int beginIndex0 = beginIndex; int endIndex0 = endIndex; while (beginIndex0 < endIndex && HTTP.isWhitespace(this.buffer[beginIndex0])) { beginIndex0++; } while (endIndex0 > beginIndex0 && HTTP.isWhitespace(this.buffer[endIndex0 - 1])) { endIndex0--; } return new String(this.buffer, beginIndex0, endIndex0 - beginIndex0); } /** * {@inheritDoc} * @since 4.4 */ @Override public CharSequence subSequence(final int beginIndex, final int endIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("Negative beginIndex: " + beginIndex); } if (endIndex > this.len) { throw new IndexOutOfBoundsException("endIndex: " + endIndex + " > length: " + this.len); } if (beginIndex > endIndex) { throw new IndexOutOfBoundsException("beginIndex: " + beginIndex + " > endIndex: " + endIndex); } return CharBuffer.wrap(this.buffer, beginIndex, endIndex); } @Override public String toString() { return new String(this.buffer, 0, this.len); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/ByteArrayBuffer.java0100644 0000000 0000000 00000026701 12613456022 030423 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code len} bytes to this buffer from the given source * array starting at index {@code off}. The capacity of the buffer * is increased, if necessary, to accommodate all {@code len} bytes. * * @param b the bytes to be appended. * @param off the index of the first byte to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if {@code off} if out of * range, {@code len} is negative, or * {@code off} + {@code len} is out of range. */ public void append(final byte[] b, final int off, final int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } final int newlen = this.len + len; if (newlen > this.buffer.length) { expand(newlen); } System.arraycopy(b, off, this.buffer, this.len, len); this.len = newlen; } /** * Appends {@code b} byte to this buffer. The capacity of the buffer * is increased, if necessary, to accommodate the additional byte. * * @param b the byte to be appended. */ public void append(final int b) { final int newlen = this.len + 1; if (newlen > this.buffer.length) { expand(newlen); } this.buffer[this.len] = (byte)b; this.len = newlen; } /** * Appends {@code len} chars to this buffer from the given source * array starting at index {@code off}. The capacity of the buffer * is increased if necessary to accommodate all {@code len} chars. *

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

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

* There is no restriction on the value of {@code beginIndex} and * {@code endIndex}. If {@code beginIndex} is negative, * it has the same effect as if it were zero. If {@code endIndex} is * greater than {@link #length()}, it has the same effect as if it were * {@link #length()}. If the {@code beginIndex} is greater than * the {@code endIndex}, {@code -1} is returned. * * @param b the byte to search for. * @param from the index to start the search from. * @param to the index to finish the search at. * @return the index of the first occurrence of the byte in the buffer * within the given bounds, or {@code -1} if the byte does * not occur. * * @since 4.1 */ public int indexOf(final byte b, final int from, final int to) { int beginIndex = from; if (beginIndex < 0) { beginIndex = 0; } int endIndex = to; if (endIndex > this.len) { endIndex = this.len; } if (beginIndex > endIndex) { return -1; } for (int i = beginIndex; i < endIndex; i++) { if (this.buffer[i] == b) { return i; } } return -1; } /** * Returns the index within this buffer of the first occurrence of the * specified byte, starting the search at {@code 0} and finishing * at {@link #length()}. If no such byte occurs in this buffer within * those bounds, {@code -1} is returned. * * @param b the byte to search for. * @return the index of the first occurrence of the byte in the * buffer, or {@code -1} if the byte does not occur. * * @since 4.1 */ public int indexOf(final byte b) { return indexOf(b, 0, this.len); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/util/LangUtils.java0100644 0000000 0000000 00000006614 12613456022 027272 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/impl/0040755 0000000 0000000 00000000000 12613456020 024503 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/EnglishReasonPhraseCatalog.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/EnglishReasonPhraseCatalog.jav0100644 0000000 0000000 00000020033 12613456020 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.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 {@code null} */ @Override public String getReason(final int status, final Locale loc) { Args.check(status >= 100 && status < 600, "Unknown category for status code " + status); final int category = status / 100; final int subcode = status - 100*category; String reason = null; if (REASON_PHRASES[category].length > subcode) { reason = REASON_PHRASES[category][subcode]; } return reason; } /** Reason phrases lookup table. */ private static final String[][] REASON_PHRASES = new String[][]{ null, new String[3], // 1xx new String[8], // 2xx new String[8], // 3xx new String[25], // 4xx new String[8] // 5xx }; /** * Stores the given reason phrase, by status code. * Helper method to initialize the static lookup table. * * @param status the status code for which to define the phrase * @param reason the reason phrase for this status code */ private static void setReason(final int status, final String reason) { final int category = status / 100; final int subcode = status - 100*category; REASON_PHRASES[category][subcode] = reason; } // ----------------------------------------------------- Static Initializer /** Set up status code to "reason phrase" map. */ static { // HTTP 1.0 Server status codes -- see RFC 1945 setReason(HttpStatus.SC_OK, "OK"); setReason(HttpStatus.SC_CREATED, "Created"); setReason(HttpStatus.SC_ACCEPTED, "Accepted"); setReason(HttpStatus.SC_NO_CONTENT, "No Content"); setReason(HttpStatus.SC_MOVED_PERMANENTLY, "Moved Permanently"); setReason(HttpStatus.SC_MOVED_TEMPORARILY, "Moved Temporarily"); setReason(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); setReason(HttpStatus.SC_BAD_REQUEST, "Bad Request"); setReason(HttpStatus.SC_UNAUTHORIZED, "Unauthorized"); setReason(HttpStatus.SC_FORBIDDEN, "Forbidden"); setReason(HttpStatus.SC_NOT_FOUND, "Not Found"); setReason(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); setReason(HttpStatus.SC_NOT_IMPLEMENTED, "Not Implemented"); setReason(HttpStatus.SC_BAD_GATEWAY, "Bad Gateway"); setReason(HttpStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"); // HTTP 1.1 Server status codes -- see RFC 2048 setReason(HttpStatus.SC_CONTINUE, "Continue"); setReason(HttpStatus.SC_TEMPORARY_REDIRECT, "Temporary Redirect"); setReason(HttpStatus.SC_METHOD_NOT_ALLOWED, "Method Not Allowed"); setReason(HttpStatus.SC_CONFLICT, "Conflict"); setReason(HttpStatus.SC_PRECONDITION_FAILED, "Precondition Failed"); setReason(HttpStatus.SC_REQUEST_TOO_LONG, "Request Too Long"); setReason(HttpStatus.SC_REQUEST_URI_TOO_LONG, "Request-URI Too Long"); setReason(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"); setReason(HttpStatus.SC_MULTIPLE_CHOICES, "Multiple Choices"); setReason(HttpStatus.SC_SEE_OTHER, "See Other"); setReason(HttpStatus.SC_USE_PROXY, "Use Proxy"); setReason(HttpStatus.SC_PAYMENT_REQUIRED, "Payment Required"); setReason(HttpStatus.SC_NOT_ACCEPTABLE, "Not Acceptable"); setReason(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, "Proxy Authentication Required"); setReason(HttpStatus.SC_REQUEST_TIMEOUT, "Request Timeout"); setReason(HttpStatus.SC_SWITCHING_PROTOCOLS, "Switching Protocols"); setReason(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION, "Non Authoritative Information"); setReason(HttpStatus.SC_RESET_CONTENT, "Reset Content"); setReason(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); setReason(HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout"); setReason(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, "Http Version Not Supported"); setReason(HttpStatus.SC_GONE, "Gone"); setReason(HttpStatus.SC_LENGTH_REQUIRED, "Length Required"); setReason(HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "Requested Range Not Satisfiable"); setReason(HttpStatus.SC_EXPECTATION_FAILED, "Expectation Failed"); // WebDAV Server-specific status codes setReason(HttpStatus.SC_PROCESSING, "Processing"); setReason(HttpStatus.SC_MULTI_STATUS, "Multi-Status"); setReason(HttpStatus.SC_UNPROCESSABLE_ENTITY, "Unprocessable Entity"); setReason(HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE, "Insufficient Space On Resource"); setReason(HttpStatus.SC_METHOD_FAILURE, "Method Failure"); setReason(HttpStatus.SC_LOCKED, "Locked"); setReason(HttpStatus.SC_INSUFFICIENT_STORAGE, "Insufficient Storage"); setReason(HttpStatus.SC_FAILED_DEPENDENCY, "Failed Dependency"); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/ConnSupport.java0100644 0000000 0000000 00000005515 12613456020 027643 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpClientConnectionFactory.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpClientConnectionFa0100644 0000000 0000000 00000010341 12613456020 032376 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override public DefaultBHttpClientConnection createConnection(final Socket socket) throws IOException { final DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection( this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), this.incomingContentStrategy, this.outgoingContentStrategy, this.requestWriterFactory, this.responseParserFactory); conn.bind(socket); return conn; } } ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultHttpResponseFactory.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultHttpResponseFactory.jav0100644 0000000 0000000 00000007556 12613456020 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 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 @Override public HttpResponse newHttpResponse( final ProtocolVersion ver, final int status, final HttpContext context) { Args.notNull(ver, "HTTP version"); final Locale loc = determineLocale(context); final String reason = this.reasonCatalog.getReason(status, loc); final StatusLine statusline = new BasicStatusLine(ver, status, reason); return new BasicHttpResponse(statusline, this.reasonCatalog, loc); } // non-javadoc, see interface HttpResponseFactory @Override public HttpResponse newHttpResponse( final StatusLine statusline, final HttpContext context) { Args.notNull(statusline, "Status line"); return new BasicHttpResponse(statusline, this.reasonCatalog, determineLocale(context)); } /** * Determines the locale of the response. * The implementation in this class always returns the default locale. * * @param context the context from which to determine the locale, or * {@code null} to use the default locale * * @return the locale for the response, never {@code null} */ protected Locale determineLocale(final HttpContext context) { return Locale.getDefault(); } } ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/NoConnectionReuseStrategy.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/NoConnectionReuseStrategy.java0100644 0000000 0000000 00000003464 12613456020 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 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(); } @Override public boolean keepAlive(final HttpResponse response, final HttpContext context) { return false; } } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpClientConnection.j0100644 0000000 0000000 00000016554 12613456020 032373 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If {@code null} * {@link org.apache.http.impl.entity.LaxContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If {@code null} * {@link org.apache.http.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used. * @param requestWriterFactory request writer factory. If {@code null} * {@link DefaultHttpRequestWriterFactory#INSTANCE} will be used. * @param responseParserFactory response parser factory. If {@code null} * {@link DefaultHttpResponseParserFactory#INSTANCE} will be used. */ public DefaultBHttpClientConnection( final int buffersize, final int fragmentSizeHint, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final HttpMessageWriterFactory requestWriterFactory, final HttpMessageParserFactory responseParserFactory) { super(buffersize, fragmentSizeHint, chardecoder, charencoder, constraints, incomingContentStrategy, outgoingContentStrategy); this.requestWriter = (requestWriterFactory != null ? requestWriterFactory : DefaultHttpRequestWriterFactory.INSTANCE).create(getSessionOutputBuffer()); this.responseParser = (responseParserFactory != null ? responseParserFactory : DefaultHttpResponseParserFactory.INSTANCE).create(getSessionInputBuffer(), constraints); } public DefaultBHttpClientConnection( final int buffersize, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints) { this(buffersize, buffersize, chardecoder, charencoder, constraints, null, null, null, null); } public DefaultBHttpClientConnection(final int buffersize) { this(buffersize, buffersize, null, null, null, null, null, null, null); } protected void onResponseReceived(final HttpResponse response) { } protected void onRequestSubmitted(final HttpRequest request) { } @Override public void bind(final Socket socket) throws IOException { super.bind(socket); } @Override public boolean isResponseAvailable(final int timeout) throws IOException { ensureOpen(); try { return awaitInput(timeout); } catch (final SocketTimeoutException ex) { return false; } } @Override public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException { Args.notNull(request, "HTTP request"); ensureOpen(); this.requestWriter.write(request); onRequestSubmitted(request); incrementRequestCount(); } @Override public void sendRequestEntity(final HttpEntityEnclosingRequest request) throws HttpException, IOException { Args.notNull(request, "HTTP request"); ensureOpen(); final HttpEntity entity = request.getEntity(); if (entity == null) { return; } final OutputStream outstream = prepareOutput(request); entity.writeTo(outstream); outstream.close(); } @Override public HttpResponse receiveResponseHeader() throws HttpException, IOException { ensureOpen(); final HttpResponse response = this.responseParser.parse(); onResponseReceived(response); if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) { incrementResponseCount(); } return response; } @Override public void receiveResponseEntity( final HttpResponse response) throws HttpException, IOException { Args.notNull(response, "HTTP response"); ensureOpen(); final HttpEntity entity = prepareInput(response); response.setEntity(entity); } @Override public void flush() throws IOException { ensureOpen(); doFlush(); } } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpServerConnection.j0100644 0000000 0000000 00000016272 12613456020 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.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 {@code null} simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If {@code null} * {@link DisallowIdentityContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If {@code null} * {@link org.apache.http.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used. * @param requestParserFactory request parser factory. If {@code null} * {@link DefaultHttpRequestParserFactory#INSTANCE} will be used. * @param responseWriterFactory response writer factory. If {@code null} * {@link DefaultHttpResponseWriterFactory#INSTANCE} will be used. */ public DefaultBHttpServerConnection( final int buffersize, final int fragmentSizeHint, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final HttpMessageParserFactory requestParserFactory, final HttpMessageWriterFactory responseWriterFactory) { super(buffersize, fragmentSizeHint, chardecoder, charencoder, constraints, incomingContentStrategy != null ? incomingContentStrategy : DisallowIdentityContentLengthStrategy.INSTANCE, outgoingContentStrategy); this.requestParser = (requestParserFactory != null ? requestParserFactory : DefaultHttpRequestParserFactory.INSTANCE).create(getSessionInputBuffer(), constraints); this.responseWriter = (responseWriterFactory != null ? responseWriterFactory : DefaultHttpResponseWriterFactory.INSTANCE).create(getSessionOutputBuffer()); } public DefaultBHttpServerConnection( final int buffersize, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints) { this(buffersize, buffersize, chardecoder, charencoder, constraints, null, null, null, null); } public DefaultBHttpServerConnection(final int buffersize) { this(buffersize, buffersize, null, null, null, null, null, null, null); } protected void onRequestReceived(final HttpRequest request) { } protected void onResponseSubmitted(final HttpResponse response) { } @Override public void bind(final Socket socket) throws IOException { super.bind(socket); } @Override public HttpRequest receiveRequestHeader() throws HttpException, IOException { ensureOpen(); final HttpRequest request = this.requestParser.parse(); onRequestReceived(request); incrementRequestCount(); return request; } @Override public void receiveRequestEntity(final HttpEntityEnclosingRequest request) throws HttpException, IOException { Args.notNull(request, "HTTP request"); ensureOpen(); final HttpEntity entity = prepareInput(request); request.setEntity(entity); } @Override public void sendResponseHeader(final HttpResponse response) throws HttpException, IOException { Args.notNull(response, "HTTP response"); ensureOpen(); this.responseWriter.write(response); onResponseSubmitted(response); if (response.getStatusLine().getStatusCode() >= 200) { incrementResponseCount(); } } @Override public void sendResponseEntity(final HttpResponse response) throws HttpException, IOException { Args.notNull(response, "HTTP response"); ensureOpen(); final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final OutputStream outstream = prepareOutput(response); entity.writeTo(outstream); outstream.close(); } @Override public void flush() throws IOException { ensureOpen(); doFlush(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/package-info.java0100644 0000000 0000000 00000002442 12613456020 027671 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultHttpRequestFactory.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultHttpRequestFactory.java0100644 0000000 0000000 00000007442 12613456020 032477 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; } @Override public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException { Args.notNull(requestline, "Request line"); final String method = requestline.getMethod(); if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(requestline); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(requestline); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(requestline); } else { throw new MethodNotSupportedException(method + " method not supported"); } } @Override public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException { if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(method, uri); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(method, uri); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(method, uri); } else { throw new MethodNotSupportedException(method + " method not supported"); } } } ././@LongLink0100644 0000000 0000000 00000000157 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpServerConnectionFactory.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultBHttpServerConnectionFa0100644 0000000 0000000 00000010341 12613456020 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.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); } @Override public DefaultBHttpServerConnection createConnection(final Socket socket) throws IOException { final DefaultBHttpServerConnection conn = new DefaultBHttpServerConnection( this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), this.incomingContentStrategy, this.outgoingContentStrategy, this.requestParserFactory, this.responseWriterFactory); conn.bind(socket); return conn; } } ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/HttpConnectionMetricsImpl.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/HttpConnectionMetricsImpl.java0100644 0000000 0000000 00000011616 12613456020 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; 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 -------------------------- */ @Override public long getReceivedBytesCount() { if (this.inTransportMetric != null) { return this.inTransportMetric.getBytesTransferred(); } else { return -1; } } @Override public long getSentBytesCount() { if (this.outTransportMetric != null) { return this.outTransportMetric.getBytesTransferred(); } else { return -1; } } @Override public long getRequestCount() { return this.requestCount; } public void incrementRequestCount() { this.requestCount++; } @Override public long getResponseCount() { return this.responseCount; } public void incrementResponseCount() { this.responseCount++; } @Override public Object getMetric(final String metricName) { Object value = null; if (this.metricsCache != null) { value = this.metricsCache.get(metricName); } if (value == null) { if (REQUEST_COUNT.equals(metricName)) { value = Long.valueOf(requestCount); } else if (RESPONSE_COUNT.equals(metricName)) { value = Long.valueOf(responseCount); } else if (RECEIVED_BYTES_COUNT.equals(metricName)) { if (this.inTransportMetric != null) { return Long.valueOf(this.inTransportMetric.getBytesTransferred()); } else { return null; } } else if (SENT_BYTES_COUNT.equals(metricName)) { if (this.outTransportMetric != null) { return Long.valueOf(this.outTransportMetric.getBytesTransferred()); } else { return null; } } } return value; } public void setMetric(final String metricName, final Object obj) { if (this.metricsCache == null) { this.metricsCache = new HashMap(); } this.metricsCache.put(metricName, obj); } @Override public void reset() { if (this.outTransportMetric != null) { this.outTransportMetric.reset(); } if (this.inTransportMetric != null) { this.inTransportMetric.reset(); } this.requestCount = 0; this.responseCount = 0; this.metricsCache = null; } } ././@LongLink0100644 0000000 0000000 00000000152 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategy.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategy0100644 0000000 0000000 00000020165 12613456020 032562 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.BasicHeaderIterator; 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 {@code Connection} header will * be examined. In the absence of a {@code Connection} header, the * non-standard but commonly used {@code Proxy-Connection} header takes * it's role. A token {@code close} indicates that the connection cannot * be reused. If there is no such token, a token {@code keep-alive} * indicates that the connection should be re-used. If neither token is found, * or if there are no {@code Connection} headers, the default policy for * the HTTP version is applied. Since {@code HTTP/1.1}, connections are * re-used by default. Up until {@code HTTP/1.0}, connections are not * re-used by default. * * @since 4.0 */ @Immutable public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy { public static final DefaultConnectionReuseStrategy INSTANCE = new DefaultConnectionReuseStrategy(); public DefaultConnectionReuseStrategy() { super(); } // see interface ConnectionReuseStrategy @Override public boolean keepAlive(final HttpResponse response, final HttpContext context) { Args.notNull(response, "HTTP response"); Args.notNull(context, "HTTP context"); // Check for a self-terminating entity. If the end of the entity will // be indicated by closing the connection, there is no keep-alive. final ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); final Header teh = response.getFirstHeader(HTTP.TRANSFER_ENCODING); if (teh != null) { if (!HTTP.CHUNK_CODING.equalsIgnoreCase(teh.getValue())) { return false; } } else { if (canResponseHaveBody(response)) { final Header[] clhs = response.getHeaders(HTTP.CONTENT_LEN); // Do not reuse if not properly content-length delimited if (clhs.length == 1) { final Header clh = clhs[0]; try { final int contentLen = Integer.parseInt(clh.getValue()); if (contentLen < 0) { return false; } } catch (final NumberFormatException ex) { return false; } } else { return false; } } } // Check for the "Connection" header. If that is absent, check for // the "Proxy-Connection" header. The latter is an unspecified and // broken but unfortunately common extension of HTTP. Header[] connHeaders = response.getHeaders(HTTP.CONN_DIRECTIVE); if (connHeaders.length == 0) { connHeaders = response.getHeaders("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 (connHeaders.length != 0) { try { final TokenIterator ti = new BasicTokenIterator(new BasicHeaderIterator(connHeaders, null)); 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; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/BHttpConnectionBase.java0100644 0000000 0000000 00000035527 12613456020 031213 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 java.util.concurrent.atomic.AtomicReference; import org.apache.http.ConnectionClosedException; 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.EmptyInputStream; 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.NetUtils; /** * This class serves as a base for all {@link HttpConnection} implementations and provides * functionality common to both client and server HTTP connections. * * @since 4.0 */ @NotThreadSafe public class BHttpConnectionBase implements HttpConnection, HttpInetConnection { private final SessionInputBufferImpl inbuffer; private final SessionOutputBufferImpl outbuffer; private final MessageConstraints messageConstraints; private final HttpConnectionMetricsImpl connMetrics; private final ContentLengthStrategy incomingContentStrategy; private final ContentLengthStrategy outgoingContentStrategy; private final AtomicReference socketHolder; /** * Creates new instance of BHttpConnectionBase. * * @param buffersize buffer size. Must be a positive number. * @param fragmentSizeHint fragment size hint. * @param chardecoder decoder to be used for decoding HTTP protocol elements. * If {@code null} simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. * @param messageConstraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If {@code null} * {@link LaxContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If {@code null} * {@link StrictContentLengthStrategy#INSTANCE} will be used. */ protected BHttpConnectionBase( final int buffersize, final int fragmentSizeHint, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints messageConstraints, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy) { super(); Args.positive(buffersize, "Buffer size"); final HttpTransportMetricsImpl inTransportMetrics = new HttpTransportMetricsImpl(); final HttpTransportMetricsImpl outTransportMetrics = new HttpTransportMetricsImpl(); this.inbuffer = new SessionInputBufferImpl(inTransportMetrics, buffersize, -1, messageConstraints != null ? messageConstraints : MessageConstraints.DEFAULT, chardecoder); this.outbuffer = new SessionOutputBufferImpl(outTransportMetrics, buffersize, fragmentSizeHint, charencoder); this.messageConstraints = messageConstraints; this.connMetrics = new HttpConnectionMetricsImpl(inTransportMetrics, outTransportMetrics); this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy : LaxContentLengthStrategy.INSTANCE; this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy : StrictContentLengthStrategy.INSTANCE; this.socketHolder = new AtomicReference(); } protected void ensureOpen() throws IOException { final Socket socket = this.socketHolder.get(); if (socket == null) { throw new ConnectionClosedException("Connection is closed"); } if (!this.inbuffer.isBound()) { this.inbuffer.bind(getSocketInputStream(socket)); } if (!this.outbuffer.isBound()) { this.outbuffer.bind(getSocketOutputStream(socket)); } } protected InputStream getSocketInputStream(final Socket socket) throws IOException { return socket.getInputStream(); } protected OutputStream getSocketOutputStream(final Socket socket) throws IOException { return socket.getOutputStream(); } /** * Binds this connection to the given {@link Socket}. This socket will be * used by the connection to send and receive data. *

* After this method's execution the connection status will be reported * as open and the {@link #isOpen()} will return {@code true}. * * @param socket the socket. * @throws IOException in case of an I/O error. */ protected void bind(final Socket socket) throws IOException { Args.notNull(socket, "Socket"); this.socketHolder.set(socket); this.inbuffer.bind(null); this.outbuffer.bind(null); } protected SessionInputBuffer getSessionInputBuffer() { return this.inbuffer; } protected SessionOutputBuffer getSessionOutputBuffer() { return this.outbuffer; } protected void doFlush() throws IOException { this.outbuffer.flush(); } @Override public boolean isOpen() { return this.socketHolder.get() != null; } protected Socket getSocket() { return this.socketHolder.get(); } protected OutputStream createOutputStream( final long len, final SessionOutputBuffer outbuffer) { if (len == ContentLengthStrategy.CHUNKED) { return new ChunkedOutputStream(2048, outbuffer); } else if (len == ContentLengthStrategy.IDENTITY) { return new IdentityOutputStream(outbuffer); } else { return new ContentLengthOutputStream(outbuffer, len); } } protected OutputStream prepareOutput(final HttpMessage message) throws HttpException { final long len = this.outgoingContentStrategy.determineLength(message); return createOutputStream(len, this.outbuffer); } protected InputStream createInputStream( final long len, final SessionInputBuffer inbuffer) { if (len == ContentLengthStrategy.CHUNKED) { return new ChunkedInputStream(inbuffer, this.messageConstraints); } else if (len == ContentLengthStrategy.IDENTITY) { return new IdentityInputStream(inbuffer); } else if (len == 0L) { return EmptyInputStream.INSTANCE; } else { return new ContentLengthInputStream(inbuffer, len); } } protected HttpEntity prepareInput(final HttpMessage message) throws HttpException { final BasicHttpEntity entity = new BasicHttpEntity(); final long len = this.incomingContentStrategy.determineLength(message); final InputStream instream = createInputStream(len, this.inbuffer); if (len == ContentLengthStrategy.CHUNKED) { entity.setChunked(true); entity.setContentLength(-1); entity.setContent(instream); } else if (len == ContentLengthStrategy.IDENTITY) { entity.setChunked(false); entity.setContentLength(-1); entity.setContent(instream); } else { entity.setChunked(false); entity.setContentLength(len); entity.setContent(instream); } final Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE); if (contentTypeHeader != null) { entity.setContentType(contentTypeHeader); } final Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING); if (contentEncodingHeader != null) { entity.setContentEncoding(contentEncodingHeader); } return entity; } @Override public InetAddress getLocalAddress() { final Socket socket = this.socketHolder.get(); return socket != null ? socket.getLocalAddress() : null; } @Override public int getLocalPort() { final Socket socket = this.socketHolder.get(); return socket != null ? socket.getLocalPort() : -1; } @Override public InetAddress getRemoteAddress() { final Socket socket = this.socketHolder.get(); return socket != null ? socket.getInetAddress() : null; } @Override public int getRemotePort() { final Socket socket = this.socketHolder.get(); return socket != null ? socket.getPort() : -1; } @Override public void setSocketTimeout(final int timeout) { final Socket socket = this.socketHolder.get(); if (socket != null) { try { socket.setSoTimeout(timeout); } catch (final SocketException ignore) { // It is not quite clear from the Sun's documentation if there are any // other legitimate cases for a socket exception to be thrown when setting // SO_TIMEOUT besides the socket being already closed } } } @Override public int getSocketTimeout() { final Socket socket = this.socketHolder.get(); if (socket != null) { try { return socket.getSoTimeout(); } catch (final SocketException ignore) { return -1; } } else { return -1; } } @Override public void shutdown() throws IOException { final Socket socket = this.socketHolder.getAndSet(null); if (socket != null) { // force abortive close (RST) try { socket.setSoLinger(true, 0); } catch (IOException ex) { } finally { socket.close(); } } } @Override public void close() throws IOException { final Socket socket = this.socketHolder.getAndSet(null); if (socket != null) { try { this.inbuffer.clear(); this.outbuffer.flush(); try { try { socket.shutdownOutput(); } catch (final IOException ignore) { } try { socket.shutdownInput(); } catch (final IOException ignore) { } } catch (final UnsupportedOperationException ignore) { // if one isn't supported, the other one isn't either } } finally { socket.close(); } } } private int fillInputBuffer(final int timeout) throws IOException { final Socket socket = this.socketHolder.get(); final int oldtimeout = socket.getSoTimeout(); try { socket.setSoTimeout(timeout); return this.inbuffer.fillBuffer(); } finally { socket.setSoTimeout(oldtimeout); } } protected boolean awaitInput(final int timeout) throws IOException { if (this.inbuffer.hasBufferedData()) { return true; } fillInputBuffer(timeout); return this.inbuffer.hasBufferedData(); } @Override public boolean isStale() { if (!isOpen()) { return true; } try { final int bytesRead = fillInputBuffer(1); return bytesRead < 0; } catch (final SocketTimeoutException ex) { return false; } catch (final IOException ex) { return true; } } protected void incrementRequestCount() { this.connMetrics.incrementRequestCount(); } protected void incrementResponseCount() { this.connMetrics.incrementResponseCount(); } @Override public HttpConnectionMetrics getMetrics() { return this.connMetrics; } @Override public String toString() { final Socket socket = this.socketHolder.get(); if (socket != null) { final StringBuilder buffer = new StringBuilder(); final SocketAddress remoteAddress = socket.getRemoteSocketAddress(); final SocketAddress localAddress = socket.getLocalSocketAddress(); if (remoteAddress != null && localAddress != null) { NetUtils.formatAddress(buffer, localAddress); buffer.append("<->"); NetUtils.formatAddress(buffer, remoteAddress); } return buffer.toString(); } else { return "[Not bound]"; } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/0040755 0000000 0000000 00000000000 12613456020 026520 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/SSLServerSetupHandler.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/SSLServerSetupHandle0100644 0000000 0000000 00000003307 12613456020 032430 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.bootstrap; import javax.net.ssl.SSLException; import javax.net.ssl.SSLServerSocket; /** * Server SSL setup handler. Custom implementations of this interface can be used to * configure various SSL protocol aspects such as supported protocol versions, cypher suites, * and mandatory / optional client authentication. * * @see javax.net.ssl.SSLServerSocket * @see javax.net.ssl.SSLSession * @since 4.4 */ public interface SSLServerSetupHandler { void initialize(SSLServerSocket socket) throws SSLException; } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/HttpServer.java0100644 0000000 0000000 00000015626 12613456020 031500 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.bootstrap; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.net.ServerSocketFactory; import javax.net.ssl.SSLServerSocket; import org.apache.http.ExceptionLogger; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpServerConnection; import org.apache.http.config.SocketConfig; import org.apache.http.impl.DefaultBHttpServerConnection; import org.apache.http.protocol.HttpService; /** * @since 4.4 */ public class HttpServer { enum Status { READY, ACTIVE, STOPPING } private final int port; private final InetAddress ifAddress; private final SocketConfig socketConfig; private final ServerSocketFactory serverSocketFactory; private final HttpService httpService; private final HttpConnectionFactory connectionFactory; private final SSLServerSetupHandler sslSetupHandler; private final ExceptionLogger exceptionLogger; private final ExecutorService listenerExecutorService; private final ThreadGroup workerThreads; private final ExecutorService workerExecutorService; private final AtomicReference status; private volatile ServerSocket serverSocket; private volatile RequestListener requestListener; HttpServer( final int port, final InetAddress ifAddress, final SocketConfig socketConfig, final ServerSocketFactory serverSocketFactory, final HttpService httpService, final HttpConnectionFactory connectionFactory, final SSLServerSetupHandler sslSetupHandler, final ExceptionLogger exceptionLogger) { this.port = port; this.ifAddress = ifAddress; this.socketConfig = socketConfig; this.serverSocketFactory = serverSocketFactory; this.httpService = httpService; this.connectionFactory = connectionFactory; this.sslSetupHandler = sslSetupHandler; this.exceptionLogger = exceptionLogger; this.listenerExecutorService = Executors.newSingleThreadExecutor( new ThreadFactoryImpl("HTTP-listener-" + this.port)); this.workerThreads = new ThreadGroup("HTTP-workers"); this.workerExecutorService = Executors.newCachedThreadPool( new ThreadFactoryImpl("HTTP-worker", this.workerThreads)); this.status = new AtomicReference(Status.READY); } public InetAddress getInetAddress() { final ServerSocket localSocket = this.serverSocket; if (localSocket != null) { return localSocket.getInetAddress(); } else { return null; } } public int getLocalPort() { final ServerSocket localSocket = this.serverSocket; if (localSocket != null) { return localSocket.getLocalPort(); } else { return -1; } } public void start() throws IOException { if (this.status.compareAndSet(Status.READY, Status.ACTIVE)) { this.serverSocket = this.serverSocketFactory.createServerSocket( this.port, this.socketConfig.getBacklogSize(), this.ifAddress); this.serverSocket.setReuseAddress(this.socketConfig.isSoReuseAddress()); if (this.socketConfig.getRcvBufSize() > 0) { this.serverSocket.setReceiveBufferSize(this.socketConfig.getRcvBufSize()); } if (this.sslSetupHandler != null && this.serverSocket instanceof SSLServerSocket) { this.sslSetupHandler.initialize((SSLServerSocket) this.serverSocket); } this.requestListener = new RequestListener( this.socketConfig, this.serverSocket, this.httpService, this.connectionFactory, this.exceptionLogger, this.workerExecutorService); this.listenerExecutorService.execute(this.requestListener); } } public void stop() { if (this.status.compareAndSet(Status.ACTIVE, Status.STOPPING)) { final RequestListener local = this.requestListener; if (local != null) { try { local.terminate(); } catch (IOException ex) { this.exceptionLogger.log(ex); } } this.workerThreads.interrupt(); this.listenerExecutorService.shutdown(); this.workerExecutorService.shutdown(); } } public void awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException { this.workerExecutorService.awaitTermination(timeout, timeUnit); } public void shutdown(final long gracePeriod, final TimeUnit timeUnit) { stop(); if (gracePeriod > 0) { try { awaitTermination(gracePeriod, timeUnit); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } final List runnables = this.workerExecutorService.shutdownNow(); for (Runnable runnable: runnables) { if (runnable instanceof Worker) { final Worker worker = (Worker) runnable; final HttpServerConnection conn = worker.getConnection(); try { conn.shutdown(); } catch (IOException ex) { this.exceptionLogger.log(ex); } } } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/package-info.java0100644 0000000 0000000 00000002372 12613456020 031710 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ /** * Embedded server and server bootstrap. */ package org.apache.http.impl.bootstrap; ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/RequestListener.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/RequestListener.java0100644 0000000 0000000 00000010202 12613456020 032511 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.bootstrap; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.http.ExceptionLogger; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpServerConnection; import org.apache.http.config.SocketConfig; import org.apache.http.protocol.HttpService; /** * @since 4.4 */ class RequestListener implements Runnable { private final SocketConfig socketConfig; private final ServerSocket serversocket; private final HttpService httpService; private final HttpConnectionFactory connectionFactory; private final ExceptionLogger exceptionLogger; private final ExecutorService executorService; private final AtomicBoolean terminated; public RequestListener( final SocketConfig socketConfig, final ServerSocket serversocket, final HttpService httpService, final HttpConnectionFactory connectionFactory, final ExceptionLogger exceptionLogger, final ExecutorService executorService) { this.socketConfig = socketConfig; this.serversocket = serversocket; this.connectionFactory = connectionFactory; this.httpService = httpService; this.exceptionLogger = exceptionLogger; this.executorService = executorService; this.terminated = new AtomicBoolean(false); } @Override public void run() { try { while (!isTerminated() && !Thread.interrupted()) { final Socket socket = this.serversocket.accept(); socket.setSoTimeout(this.socketConfig.getSoTimeout()); socket.setKeepAlive(this.socketConfig.isSoKeepAlive()); socket.setTcpNoDelay(this.socketConfig.isTcpNoDelay()); if (this.socketConfig.getRcvBufSize() > 0) { socket.setReceiveBufferSize(this.socketConfig.getRcvBufSize()); } if (this.socketConfig.getSndBufSize() > 0) { socket.setSendBufferSize(this.socketConfig.getSndBufSize()); } if (this.socketConfig.getSoLinger() >= 0) { socket.setSoLinger(true, this.socketConfig.getSoLinger()); } final HttpServerConnection conn = this.connectionFactory.createConnection(socket); final Worker worker = new Worker(this.httpService, conn, this.exceptionLogger); this.executorService.execute(worker); } } catch (Exception ex) { this.exceptionLogger.log(ex); } } public boolean isTerminated() { return this.terminated.get(); } public void terminate() throws IOException { if (this.terminated.compareAndSet(false, true)) { this.serversocket.close(); } } } ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/ServerBootstrap.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/ServerBootstrap.java0100644 0000000 0000000 00000034630 12613456020 032532 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.bootstrap; import java.net.InetAddress; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import javax.net.ServerSocketFactory; import javax.net.ssl.SSLContext; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.ExceptionLogger; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpResponseInterceptor; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.SocketConfig; import org.apache.http.impl.DefaultBHttpServerConnection; import org.apache.http.impl.DefaultBHttpServerConnectionFactory; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpRequestHandlerMapper; 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; /** * @since 4.4 */ public class ServerBootstrap { private int listenerPort; private InetAddress localAddress; private SocketConfig socketConfig; private ConnectionConfig connectionConfig; private LinkedList requestFirst; private LinkedList requestLast; private LinkedList responseFirst; private LinkedList responseLast; private String serverInfo; private HttpProcessor httpProcessor; private ConnectionReuseStrategy connStrategy; private HttpResponseFactory responseFactory; private HttpRequestHandlerMapper handlerMapper; private Map handlerMap; private HttpExpectationVerifier expectationVerifier; private ServerSocketFactory serverSocketFactory; private SSLContext sslContext; private SSLServerSetupHandler sslSetupHandler; private HttpConnectionFactory connectionFactory; private ExceptionLogger exceptionLogger; private ServerBootstrap() { } public static ServerBootstrap bootstrap() { return new ServerBootstrap(); } /** * Sets listener port number. */ public final ServerBootstrap setListenerPort(final int listenerPort) { this.listenerPort = listenerPort; return this; } /** * Assigns local interface for the listener. */ public final ServerBootstrap setLocalAddress(final InetAddress localAddress) { this.localAddress = localAddress; return this; } /** * Sets socket configuration. */ public final ServerBootstrap setSocketConfig(final SocketConfig socketConfig) { this.socketConfig = socketConfig; return this; } /** * Sets connection configuration. *

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

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

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

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

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

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

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

* Please note this value can be overridden by the {@link #setServerSocketFactory( * javax.net.ServerSocketFactory)} method. */ public final ServerBootstrap setSslContext(final SSLContext sslContext) { this.sslContext = sslContext; return this; } /** * Assigns {@link org.apache.http.ExceptionLogger} instance. */ public final ServerBootstrap setExceptionLogger(final ExceptionLogger exceptionLogger) { this.exceptionLogger = exceptionLogger; return this; } public HttpServer create() { HttpProcessor httpProcessorCopy = this.httpProcessor; if (httpProcessorCopy == null) { final HttpProcessorBuilder b = HttpProcessorBuilder.create(); if (requestFirst != null) { for (final HttpRequestInterceptor i: requestFirst) { b.addFirst(i); } } if (responseFirst != null) { for (final HttpResponseInterceptor i: responseFirst) { b.addFirst(i); } } String serverInfoCopy = this.serverInfo; if (serverInfoCopy == null) { serverInfoCopy = "Apache-HttpCore/1.1"; } b.addAll( new ResponseDate(), new ResponseServer(serverInfoCopy), new ResponseContent(), new ResponseConnControl()); if (requestLast != null) { for (final HttpRequestInterceptor i: requestLast) { b.addLast(i); } } if (responseLast != null) { for (final HttpResponseInterceptor i: responseLast) { b.addLast(i); } } httpProcessorCopy = b.build(); } HttpRequestHandlerMapper handlerMapperCopy = this.handlerMapper; if (handlerMapperCopy == null) { final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); if (handlerMap != null) { for (Map.Entry entry: handlerMap.entrySet()) { reqistry.register(entry.getKey(), entry.getValue()); } } handlerMapperCopy = reqistry; } ConnectionReuseStrategy connStrategyCopy = this.connStrategy; if (connStrategyCopy == null) { connStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE; } HttpResponseFactory responseFactoryCopy = this.responseFactory; if (responseFactoryCopy == null) { responseFactoryCopy = DefaultHttpResponseFactory.INSTANCE; } final HttpService httpService = new HttpService( httpProcessorCopy, connStrategyCopy, responseFactoryCopy, handlerMapperCopy, this.expectationVerifier); ServerSocketFactory serverSocketFactoryCopy = this.serverSocketFactory; if (serverSocketFactoryCopy == null) { if (this.sslContext != null) { serverSocketFactoryCopy = this.sslContext.getServerSocketFactory(); } else { serverSocketFactoryCopy = ServerSocketFactory.getDefault(); } } HttpConnectionFactory connectionFactoryCopy = this.connectionFactory; if (connectionFactoryCopy == null) { if (this.connectionConfig != null) { connectionFactoryCopy = new DefaultBHttpServerConnectionFactory(this.connectionConfig); } else { connectionFactoryCopy = DefaultBHttpServerConnectionFactory.INSTANCE; } } ExceptionLogger exceptionLoggerCopy = this.exceptionLogger; if (exceptionLoggerCopy == null) { exceptionLoggerCopy = ExceptionLogger.NO_OP; } return new HttpServer( this.listenerPort > 0 ? this.listenerPort : 0, this.localAddress, this.socketConfig != null ? this.socketConfig : SocketConfig.DEFAULT, serverSocketFactoryCopy, httpService, connectionFactoryCopy, this.sslSetupHandler, exceptionLoggerCopy); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/Worker.java0100644 0000000 0000000 00000005275 12613456020 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.impl.bootstrap; import java.io.IOException; import org.apache.http.ExceptionLogger; import org.apache.http.HttpServerConnection; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpService; /** * @since 4.4 */ class Worker implements Runnable { private final HttpService httpservice; private final HttpServerConnection conn; private final ExceptionLogger exceptionLogger; Worker( final HttpService httpservice, final HttpServerConnection conn, final ExceptionLogger exceptionLogger) { super(); this.httpservice = httpservice; this.conn = conn; this.exceptionLogger = exceptionLogger; } public HttpServerConnection getConnection() { return this.conn; } @Override public void run() { try { final BasicHttpContext localContext = new BasicHttpContext(); final HttpCoreContext context = HttpCoreContext.adapt(localContext); while (!Thread.interrupted() && this.conn.isOpen()) { this.httpservice.handleRequest(this.conn, context); localContext.clear(); } this.conn.close(); } catch (Exception ex) { this.exceptionLogger.log(ex); } finally { try { this.conn.shutdown(); } catch (IOException ex) { this.exceptionLogger.log(ex); } } } } ././@LongLink0100644 0000000 0000000 00000000147 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/ThreadFactoryImpl.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/bootstrap/ThreadFactoryImpl.ja0100644 0000000 0000000 00000003641 12613456020 032416 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.bootstrap; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; /** * @since 4.4 */ class ThreadFactoryImpl implements ThreadFactory { private final String namePrefix; private final ThreadGroup group; private final AtomicLong count; ThreadFactoryImpl(final String namePrefix, final ThreadGroup group) { this.namePrefix = namePrefix; this.group = group; this.count = new AtomicLong(); } ThreadFactoryImpl(final String namePrefix) { this(namePrefix, null); } @Override public Thread newThread(final Runnable target) { return new Thread(this.group, target, this.namePrefix + "-" + this.count.incrementAndGet()); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/pool/0040755 0000000 0000000 00000000000 12613456020 025454 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/pool/package-info.java0100644 0000000 0000000 00000002463 12613456020 030645 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/impl/pool/BasicConnPool.java0100644 0000000 0000000 00000006345 12613456020 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.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); } @Override protected boolean validate(final BasicPoolEntry entry) { return !entry.getConnection().isStale(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/pool/BasicConnFactory.java0100644 0000000 0000000 00000015270 12613456020 031510 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; } @Override public HttpClientConnection create(final HttpHost host) throws IOException { final String scheme = host.getSchemeName(); Socket socket = null; if ("http".equalsIgnoreCase(scheme)) { socket = this.plainfactory != null ? this.plainfactory.createSocket() : new Socket(); } if ("https".equalsIgnoreCase(scheme)) { socket = (this.sslfactory != null ? this.sslfactory : SSLSocketFactory.getDefault()).createSocket(); } if (socket == null) { throw new IOException(scheme + " scheme is not supported"); } final String hostname = host.getHostName(); int port = host.getPort(); if (port == -1) { if (host.getSchemeName().equalsIgnoreCase("http")) { port = 80; } else if (host.getSchemeName().equalsIgnoreCase("https")) { port = 443; } } socket.setSoTimeout(this.sconfig.getSoTimeout()); if (this.sconfig.getSndBufSize() > 0) { socket.setSendBufferSize(this.sconfig.getSndBufSize()); } if (this.sconfig.getRcvBufSize() > 0) { socket.setReceiveBufferSize(this.sconfig.getRcvBufSize()); } socket.setTcpNoDelay(this.sconfig.isTcpNoDelay()); final int linger = this.sconfig.getSoLinger(); if (linger >= 0) { socket.setSoLinger(true, linger); } socket.setKeepAlive(this.sconfig.isSoKeepAlive()); socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout); return this.connFactory.createConnection(socket); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/pool/BasicPoolEntry.java0100644 0000000 0000000 00000004113 12613456020 031210 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/impl/io/0040755 0000000 0000000 00000000000 12613456020 025112 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000157 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParserFactory.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParserFa0100644 0000000 0000000 00000005333 12613456020 032425 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override public HttpMessageParser create(final SessionInputBuffer buffer, final MessageConstraints constraints) { return new DefaultHttpResponseParser(buffer, lineParser, responseFactory, constraints); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/EmptyInputStream.java0100644 0000000 0000000 00000004045 12613456020 031247 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.InputStream; /** * @since 4.4 */ public final class EmptyInputStream extends InputStream { public static final EmptyInputStream INSTANCE = new EmptyInputStream(); private EmptyInputStream() { } @Override public int available() { return 0; } @Override public void close() { } @Override public void mark(final int readLimit) { } @Override public boolean markSupported() { return true; } @Override public int read() { return -1; } @Override public int read(final byte[] buf) { return -1; } @Override public int read(final byte[] buf, final int off, final int len) { return -1; } @Override public void reset() { } @Override public long skip(final long n) { return 0L; } } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriter.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriter.j0100644 0000000 0000000 00000004615 12613456020 032430 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code 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); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/ChunkedOutputStream.java0100644 0000000 0000000 00000015404 12613456020 031734 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 00000000147 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/ContentLengthInputStream.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/ContentLengthInputStream.ja0100644 0000000 0000000 00000017337 12613456020 032406 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Content-Length header}. * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE} * long. *

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

Reads until the end of the known length of content.

* *

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

* @throws IOException If an IO problem occurs. */ @Override public void close() throws IOException { if (!closed) { try { if (pos < contentLength) { final byte buffer[] = new byte[BUFFER_SIZE]; while (read(buffer) >= 0) { } } } finally { // close after above so that we don't throw an exception trying // to read after closed! closed = true; } } } @Override public int available() throws IOException { if (this.in instanceof BufferInfo) { final int len = ((BufferInfo) this.in).length(); return Math.min(len, (int) (this.contentLength - this.pos)); } else { return 0; } } /** * Read the next byte from the stream * @return The next byte or -1 if the end of stream has been reached. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read() */ @Override public int read() throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } final int b = this.in.read(); if (b == -1) { if (pos < contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + contentLength + "; received: " + pos); } } else { pos++; } return b; } /** * Does standard {@link InputStream#read(byte[], int, int)} behavior, but * also notifies the watcher when the contents have been consumed. * * @param b The byte array to fill. * @param off Start filling at this position. * @param len The number of bytes to attempt to read. * @return The number of bytes read, or -1 if the end of content has been * reached. * * @throws java.io.IOException Should an error occur on the wrapped stream. */ @Override public int read (final byte[] b, final int off, final int len) throws java.io.IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } int chunk = len; if (pos + len > contentLength) { chunk = (int) (contentLength - pos); } final int count = this.in.read(b, off, chunk); if (count == -1 && pos < contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + contentLength + "; received: " + pos); } if (count > 0) { pos += count; } return count; } /** * Read more bytes from the stream. * @param b The byte array to put the new data in. * @return The number of bytes read into the buffer. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read(byte[]) */ @Override public int read(final byte[] b) throws IOException { return read(b, 0, b.length); } /** * Skips and discards a number of bytes from the input stream. * @param n The number of bytes to skip. * @return The actual number of bytes skipped. ≤ 0 if no bytes * are skipped. * @throws IOException If an error occurs while skipping bytes. * @see InputStream#skip(long) */ @Override public long skip(final long n) throws IOException { if (n <= 0) { return 0; } final byte[] buffer = new byte[BUFFER_SIZE]; // make sure we don't skip more bytes than are // still available long remaining = Math.min(n, this.contentLength - this.pos); // skip and keep track of the bytes actually skipped long count = 0; while (remaining > 0) { final int l = read(buffer, 0, (int)Math.min(BUFFER_SIZE, remaining)); if (l == -1) { break; } count += l; remaining -= l; } return count; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/IdentityInputStream.java0100644 0000000 0000000 00000005754 12613456020 031752 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 * {@code -1} is returned). * * @since 4.0 */ @NotThreadSafe public class IdentityInputStream extends InputStream { private final SessionInputBuffer in; private boolean closed = false; /** * Wraps session input stream and reads input until the the end of stream. * * @param in The session input buffer */ public IdentityInputStream(final SessionInputBuffer in) { super(); this.in = Args.notNull(in, "Session input buffer"); } @Override public int available() throws IOException { if (this.in instanceof BufferInfo) { return ((BufferInfo) this.in).length(); } else { return 0; } } @Override public void close() throws IOException { this.closed = true; } @Override public int read() throws IOException { if (this.closed) { return -1; } else { return this.in.read(); } } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (this.closed) { return -1; } else { return this.in.read(b, off, len); } } } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParserFactory.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParserFac0100644 0000000 0000000 00000005306 12613456020 032422 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override public HttpMessageParser create(final SessionInputBuffer buffer, final MessageConstraints constraints) { return new DefaultHttpRequestParser(buffer, lineParser, requestFactory, constraints); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/package-info.java0100644 0000000 0000000 00000002457 12613456020 030306 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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; httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/IdentityOutputStream.java0100644 0000000 0000000 00000006250 12613456020 032143 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParser.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParser.ja0100644 0000000 0000000 00000012020 12613456020 032370 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} * {@link org.apache.http.message.BasicLineParser#INSTANCE} will be used. * @param requestFactory the response factory. If {@code null} * {@link DefaultHttpRequestFactory#INSTANCE} will be used. * @param constraints the message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * * @since 4.3 */ public DefaultHttpRequestParser( final SessionInputBuffer buffer, final LineParser lineParser, final HttpRequestFactory requestFactory, final MessageConstraints constraints) { super(buffer, lineParser, constraints); this.requestFactory = requestFactory != null ? requestFactory : DefaultHttpRequestFactory.INSTANCE; this.lineBuf = new CharArrayBuffer(128); } /** * @since 4.3 */ public DefaultHttpRequestParser( final SessionInputBuffer buffer, final MessageConstraints constraints) { this(buffer, null, null, constraints); } /** * @since 4.3 */ public DefaultHttpRequestParser(final SessionInputBuffer buffer) { this(buffer, null, null, MessageConstraints.DEFAULT); } @Override protected HttpRequest parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); final int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new ConnectionClosedException("Client closed connection"); } final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); final RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor); return this.requestFactory.newHttpRequest(requestline); } } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParser.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParser.j0100644 0000000 0000000 00000012154 12613456020 032405 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} * {@link org.apache.http.message.BasicLineParser#INSTANCE} will be used * @param responseFactory the response factory. If {@code null} * {@link DefaultHttpResponseFactory#INSTANCE} will be used. * @param constraints the message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * * @since 4.3 */ public DefaultHttpResponseParser( final SessionInputBuffer buffer, final LineParser lineParser, final HttpResponseFactory responseFactory, final MessageConstraints constraints) { super(buffer, lineParser, constraints); this.responseFactory = responseFactory != null ? responseFactory : DefaultHttpResponseFactory.INSTANCE; this.lineBuf = new CharArrayBuffer(128); } /** * @since 4.3 */ public DefaultHttpResponseParser( final SessionInputBuffer buffer, final MessageConstraints constraints) { this(buffer, null, null, constraints); } /** * @since 4.3 */ public DefaultHttpResponseParser(final SessionInputBuffer buffer) { this(buffer, null, null, MessageConstraints.DEFAULT); } @Override protected HttpResponse parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); final int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new NoHttpResponseException("The target server failed to respond"); } //create the status line from the status string final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); return this.responseFactory.newHttpResponse(statusline, null); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/AbstractMessageWriter.java0100644 0000000 0000000 00000010633 12613456020 032222 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} {@link BasicLineFormatter#INSTANCE} * will be used. * * @since 4.3 */ public AbstractMessageWriter( final SessionOutputBuffer buffer, final LineFormatter formatter) { super(); this.sessionBuffer = Args.notNull(buffer, "Session input buffer"); this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatter.INSTANCE; this.lineBuf = new CharArrayBuffer(128); } /** * Subclasses must override this method to write out the first header line * based on the {@link HttpMessage} passed as a parameter. * * @param message the message whose first line is to be written out. * @throws IOException in case of an I/O error. */ protected abstract void writeHeadLine(T message) throws IOException; @Override public void write(final T message) throws IOException, HttpException { Args.notNull(message, "HTTP message"); writeHeadLine(message); for (final HeaderIterator it = message.headerIterator(); it.hasNext(); ) { final Header header = it.nextHeader(); this.sessionBuffer.writeLine (lineFormatter.formatHeader(this.lineBuf, header)); } this.lineBuf.clear(); this.sessionBuffer.writeLine(this.lineBuf); } } ././@LongLink0100644 0000000 0000000 00000000157 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriterFactory.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriterFa0100644 0000000 0000000 00000004444 12613456020 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 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); } @Override public HttpMessageWriter create(final SessionOutputBuffer buffer) { return new DefaultHttpResponseWriter(buffer, lineFormatter); } } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriterFactory.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriterFac0100644 0000000 0000000 00000004432 12613456020 032441 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override public HttpMessageWriter create(final SessionOutputBuffer buffer) { return new DefaultHttpRequestWriter(buffer, lineFormatter); } } ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/SessionOutputBufferImpl.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/SessionOutputBufferImpl.jav0100644 0000000 0000000 00000022455 12613456020 032441 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code 0} disables fragment buffering. * @param charencoder charencoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. */ public SessionOutputBufferImpl( final HttpTransportMetricsImpl metrics, final int buffersize, final int fragementSizeHint, final CharsetEncoder charencoder) { super(); Args.positive(buffersize, "Buffer size"); Args.notNull(metrics, "HTTP transport metrcis"); this.metrics = metrics; this.buffer = new ByteArrayBuffer(buffersize); this.fragementSizeHint = fragementSizeHint >= 0 ? fragementSizeHint : 0; this.encoder = charencoder; } public SessionOutputBufferImpl( final HttpTransportMetricsImpl metrics, final int buffersize) { this(metrics, buffersize, buffersize, null); } public void bind(final OutputStream outstream) { this.outstream = outstream; } public boolean isBound() { return this.outstream != null; } @Override public int capacity() { return this.buffer.capacity(); } @Override public int length() { return this.buffer.length(); } @Override public int available() { return capacity() - length(); } private void streamWrite(final byte[] b, final int off, final int len) throws IOException { Asserts.notNull(outstream, "Output stream"); this.outstream.write(b, off, len); } private void flushStream() throws IOException { if (this.outstream != null) { this.outstream.flush(); } } private void flushBuffer() throws IOException { final int len = this.buffer.length(); if (len > 0) { streamWrite(this.buffer.buffer(), 0, len); this.buffer.clear(); this.metrics.incrementBytesTransferred(len); } } @Override public void flush() throws IOException { flushBuffer(); flushStream(); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { if (b == null) { return; } // Do not want to buffer large-ish chunks // if the byte array is larger then MIN_CHUNK_LIMIT // write it directly to the output stream if (len > this.fragementSizeHint || len > this.buffer.capacity()) { // flush the buffer flushBuffer(); // write directly to the out stream streamWrite(b, off, len); this.metrics.incrementBytesTransferred(len); } else { // Do not let the buffer grow unnecessarily final int freecapacity = this.buffer.capacity() - this.buffer.length(); if (len > freecapacity) { // flush the buffer flushBuffer(); } // buffer this.buffer.append(b, off, len); } } @Override public void write(final byte[] b) throws IOException { if (b == null) { return; } write(b, 0, b.length); } @Override public void write(final int b) throws IOException { if (this.fragementSizeHint > 0) { if (this.buffer.isFull()) { flushBuffer(); } this.buffer.append(b); } else { flushBuffer(); this.outstream.write(b); } } /** * Writes characters from the specified string followed by a line delimiter * to this session buffer. *

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

* This method uses CR-LF as a line delimiter. * * @param charbuffer the buffer containing chars of the line. * @exception IOException if an I/O error occurs. */ @Override public void writeLine(final CharArrayBuffer charbuffer) throws IOException { if (charbuffer == null) { return; } if (this.encoder == null) { int off = 0; int remaining = charbuffer.length(); while (remaining > 0) { int chunk = this.buffer.capacity() - this.buffer.length(); chunk = Math.min(chunk, remaining); if (chunk > 0) { this.buffer.append(charbuffer, off, chunk); } if (this.buffer.isFull()) { flushBuffer(); } off += chunk; remaining -= chunk; } } else { final CharBuffer cbuf = CharBuffer.wrap(charbuffer.buffer(), 0, charbuffer.length()); writeEncoded(cbuf); } write(CRLF); } private void writeEncoded(final CharBuffer cbuf) throws IOException { if (!cbuf.hasRemaining()) { return; } if (this.bbuf == null) { this.bbuf = ByteBuffer.allocate(1024); } this.encoder.reset(); while (cbuf.hasRemaining()) { final CoderResult result = this.encoder.encode(cbuf, this.bbuf, true); handleEncodingResult(result); } final CoderResult result = this.encoder.flush(this.bbuf); handleEncodingResult(result); this.bbuf.clear(); } private void handleEncodingResult(final CoderResult result) throws IOException { if (result.isError()) { result.throwException(); } this.bbuf.flip(); while (this.bbuf.hasRemaining()) { write(this.bbuf.get()); } this.bbuf.compact(); } @Override public HttpTransportMetrics getMetrics() { return this.metrics; } } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/ContentLengthOutputStream.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/ContentLengthOutputStream.j0100644 0000000 0000000 00000010372 12613456020 032436 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Content-Length header}. * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE} * long. *

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

Does not close the underlying socket output.

* * @throws IOException If an I/O problem occurs. */ @Override public void close() throws IOException { if (!this.closed) { this.closed = true; this.out.flush(); } } @Override public void flush() throws IOException { this.out.flush(); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { if (this.closed) { throw new IOException("Attempted write to closed stream."); } if (this.total < this.contentLength) { final long max = this.contentLength - this.total; int chunk = len; if (chunk > max) { chunk = (int) max; } this.out.write(b, off, chunk); this.total += chunk; } } @Override public void write(final byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(final int b) throws IOException { if (this.closed) { throw new IOException("Attempted write to closed stream."); } if (this.total < this.contentLength) { this.out.write(b); this.total++; } } } ././@LongLink0100644 0000000 0000000 00000000147 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/HttpTransportMetricsImpl.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/HttpTransportMetricsImpl.ja0100644 0000000 0000000 00000003703 12613456020 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 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(); } @Override public long getBytesTransferred() { return this.bytesTransferred; } public void setBytesTransferred(final long count) { this.bytesTransferred = count; } public void incrementBytesTransferred(final long count) { this.bytesTransferred += count; } @Override public void reset() { this.bytesTransferred = 0; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/AbstractMessageParser.java0100644 0000000 0000000 00000026622 12613456020 032207 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code null} {@link BasicLineParser#INSTANCE} * will be used. * @param constraints the message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * * @since 4.3 */ public AbstractMessageParser( final SessionInputBuffer buffer, final LineParser lineParser, final MessageConstraints constraints) { super(); this.sessionBuffer = Args.notNull(buffer, "Session input buffer"); this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; this.messageConstraints = constraints != null ? constraints : MessageConstraints.DEFAULT; this.headerLines = new ArrayList(); this.state = HEAD_LINE; } /** * Parses HTTP headers from the data receiver stream according to the generic * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. * * @param inbuffer Session input buffer * @param maxHeaderCount maximum number of headers allowed. If the number * of headers received from the data stream exceeds maxCount value, an * IOException will be thrown. Setting this parameter to a negative value * or zero will disable the check. * @param maxLineLen maximum number of characters for a header line, * including the continuation lines. Setting this parameter to a negative * value or zero will disable the check. * @return array of HTTP headers * @param parser line parser to use. Can be {@code null}, in which case * the default implementation of this interface will be used. * * @throws IOException in case of an I/O error * @throws HttpException in case of HTTP protocol violation */ public static Header[] parseHeaders( final SessionInputBuffer inbuffer, final int maxHeaderCount, final int maxLineLen, final LineParser parser) throws HttpException, IOException { final List headerLines = new ArrayList(); return parseHeaders(inbuffer, maxHeaderCount, maxLineLen, parser != null ? parser : BasicLineParser.INSTANCE, headerLines); } /** * Parses HTTP headers from the data receiver stream according to the generic * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. * * @param inbuffer Session input buffer * @param maxHeaderCount maximum number of headers allowed. If the number * of headers received from the data stream exceeds maxCount value, an * IOException will be thrown. Setting this parameter to a negative value * or zero will disable the check. * @param maxLineLen maximum number of characters for a header line, * including the continuation lines. Setting this parameter to a negative * value or zero will disable the check. * @param parser line parser to use. * @param headerLines List of header lines. This list will be used to store * intermediate results. This makes it possible to resume parsing of * headers in case of a {@link java.io.InterruptedIOException}. * * @return array of HTTP headers * * @throws IOException in case of an I/O error * @throws HttpException in case of HTTP protocol violation * * @since 4.1 */ public static Header[] parseHeaders( final SessionInputBuffer inbuffer, final int maxHeaderCount, final int maxLineLen, final LineParser parser, final List headerLines) throws HttpException, IOException { Args.notNull(inbuffer, "Session input buffer"); Args.notNull(parser, "Line parser"); Args.notNull(headerLines, "Header line list"); CharArrayBuffer current = null; CharArrayBuffer previous = null; for (;;) { if (current == null) { current = new CharArrayBuffer(64); } else { current.clear(); } final int l = inbuffer.readLine(current); if (l == -1 || current.length() < 1) { break; } // Parse the header name and value // Check for folded headers first // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 // discussion on folded headers if ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) { // we have continuation folded header // so append value int i = 0; while (i < current.length()) { final char ch = current.charAt(i); if (ch != ' ' && ch != '\t') { break; } i++; } if (maxLineLen > 0 && previous.length() + 1 + current.length() - i > maxLineLen) { throw new MessageConstraintException("Maximum line length limit exceeded"); } previous.append(' '); previous.append(current, i, current.length() - i); } else { headerLines.add(current); previous = current; current = null; } if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) { throw new MessageConstraintException("Maximum header count exceeded"); } } final Header[] headers = new Header[headerLines.size()]; for (int i = 0; i < headerLines.size(); i++) { final CharArrayBuffer buffer = headerLines.get(i); try { headers[i] = parser.parseHeader(buffer); } catch (final ParseException ex) { throw new ProtocolException(ex.getMessage()); } } return headers; } /** * Subclasses must override this method to generate an instance of * {@link HttpMessage} based on the initial input from the session buffer. *

* Usually this method is expected to read just the very first line or * the very first valid from the data stream and based on the input generate * an appropriate instance of {@link HttpMessage}. * * @param sessionBuffer the session input buffer. * @return HTTP message based on the input from the session buffer. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation. * @throws ParseException in case of a parse error. */ protected abstract T parseHead(SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException; @Override public T parse() throws IOException, HttpException { final int st = this.state; switch (st) { case HEAD_LINE: try { this.message = parseHead(this.sessionBuffer); } catch (final ParseException px) { throw new ProtocolException(px.getMessage(), px); } this.state = HEADERS; //$FALL-THROUGH$ case HEADERS: final Header[] headers = AbstractMessageParser.parseHeaders( this.sessionBuffer, this.messageConstraints.getMaxHeaderCount(), this.messageConstraints.getMaxLineLength(), this.lineParser, this.headerLines); this.message.setHeaders(headers); final T result = this.message; this.message = null; this.headerLines.clear(); this.state = HEAD_LINE; return result; default: throw new IllegalStateException("Inconsistent parser state"); } } } ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/SessionInputBufferImpl.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/SessionInputBufferImpl.java0100644 0000000 0000000 00000034352 12613456020 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.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 {@code null} * {@link MessageConstraints#DEFAULT} will be used. * @param chardecoder chardecoder to be used for decoding HTTP protocol elements. * If {@code null} simple type cast will be used for byte to char conversion. */ public SessionInputBufferImpl( final HttpTransportMetricsImpl metrics, final int buffersize, final int minChunkLimit, final MessageConstraints constraints, final CharsetDecoder chardecoder) { Args.notNull(metrics, "HTTP transport metrcis"); Args.positive(buffersize, "Buffer size"); this.metrics = metrics; this.buffer = new byte[buffersize]; this.bufferpos = 0; this.bufferlen = 0; this.minChunkLimit = minChunkLimit >= 0 ? minChunkLimit : 512; this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; this.linebuffer = new ByteArrayBuffer(buffersize); this.decoder = chardecoder; } public SessionInputBufferImpl( final HttpTransportMetricsImpl metrics, final int buffersize) { this(metrics, buffersize, buffersize, null, null); } public void bind(final InputStream instream) { this.instream = instream; } public boolean isBound() { return this.instream != null; } @Override public int capacity() { return this.buffer.length; } @Override public int length() { return this.bufferlen - this.bufferpos; } @Override public int available() { return capacity() - length(); } private int streamRead(final byte[] b, final int off, final int len) throws IOException { Asserts.notNull(this.instream, "Input stream"); return this.instream.read(b, off, len); } public int fillBuffer() throws IOException { // compact the buffer if necessary if (this.bufferpos > 0) { final int len = this.bufferlen - this.bufferpos; if (len > 0) { System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len); } this.bufferpos = 0; this.bufferlen = len; } final int l; final int off = this.bufferlen; final int len = this.buffer.length - off; l = streamRead(this.buffer, off, len); if (l == -1) { return -1; } else { this.bufferlen = off + l; this.metrics.incrementBytesTransferred(l); return l; } } public boolean hasBufferedData() { return this.bufferpos < this.bufferlen; } public void clear() { this.bufferpos = 0; this.bufferlen = 0; } @Override public int read() throws IOException { int noRead; while (!hasBufferedData()) { noRead = fillBuffer(); if (noRead == -1) { return -1; } } return this.buffer[this.bufferpos++] & 0xff; } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (b == null) { return 0; } if (hasBufferedData()) { final int chunk = Math.min(len, this.bufferlen - this.bufferpos); System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); this.bufferpos += chunk; return chunk; } // If the remaining capacity is big enough, read directly from the // underlying input stream bypassing the buffer. if (len > this.minChunkLimit) { final int read = streamRead(b, off, len); if (read > 0) { this.metrics.incrementBytesTransferred(read); } return read; } else { // otherwise read to the buffer first while (!hasBufferedData()) { final int noRead = fillBuffer(); if (noRead == -1) { return -1; } } final int chunk = Math.min(len, this.bufferlen - this.bufferpos); System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); this.bufferpos += chunk; return chunk; } } @Override public int read(final byte[] b) throws IOException { if (b == null) { return 0; } return read(b, 0, b.length); } /** * Reads a complete line of characters up to a line delimiter from this * session buffer into the given line buffer. The number of chars actually * read is returned as an integer. The line delimiter itself is discarded. * If no char is available because the end of the stream has been reached, * the value {@code -1} is returned. This method blocks until input * data is available, end of file is detected, or an exception is thrown. *

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

* This method treats a lone LF as a valid line delimiters in addition * to CR-LF required by the HTTP specification. * * @return HTTP line as a string * @exception IOException if an I/O error occurs. */ private int lineFromLineBuffer(final CharArrayBuffer charbuffer) throws IOException { // discard LF if found int len = this.linebuffer.length(); if (len > 0) { if (this.linebuffer.byteAt(len - 1) == HTTP.LF) { len--; } // discard CR if found if (len > 0) { if (this.linebuffer.byteAt(len - 1) == HTTP.CR) { len--; } } } if (this.decoder == null) { charbuffer.append(this.linebuffer, 0, len); } else { final ByteBuffer bbuf = ByteBuffer.wrap(this.linebuffer.buffer(), 0, len); len = appendDecoded(charbuffer, bbuf); } this.linebuffer.clear(); return len; } private int lineFromReadBuffer(final CharArrayBuffer charbuffer, final int position) throws IOException { int pos = position; final int off = this.bufferpos; int len; this.bufferpos = pos + 1; if (pos > off && this.buffer[pos - 1] == HTTP.CR) { // skip CR if found pos--; } len = pos - off; if (this.decoder == null) { charbuffer.append(this.buffer, off, len); } else { final ByteBuffer bbuf = ByteBuffer.wrap(this.buffer, off, len); len = appendDecoded(charbuffer, bbuf); } return len; } private int appendDecoded( final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { if (!bbuf.hasRemaining()) { return 0; } if (this.cbuf == null) { this.cbuf = CharBuffer.allocate(1024); } this.decoder.reset(); int len = 0; while (bbuf.hasRemaining()) { final CoderResult result = this.decoder.decode(bbuf, this.cbuf, true); len += handleDecodingResult(result, charbuffer, bbuf); } final CoderResult result = this.decoder.flush(this.cbuf); len += handleDecodingResult(result, charbuffer, bbuf); this.cbuf.clear(); return len; } private int handleDecodingResult( final CoderResult result, final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { if (result.isError()) { result.throwException(); } this.cbuf.flip(); final int len = this.cbuf.remaining(); while (this.cbuf.hasRemaining()) { charbuffer.append(this.cbuf.get()); } this.cbuf.compact(); return len; } @Override public String readLine() throws IOException { final CharArrayBuffer charbuffer = new CharArrayBuffer(64); final int l = readLine(charbuffer); if (l != -1) { return charbuffer.toString(); } else { return null; } } @Override public boolean isDataAvailable(final int timeout) throws IOException { return hasBufferedData(); } @Override public HttpTransportMetrics getMetrics() { return this.metrics; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/ChunkedInputStream.java0100644 0000000 0000000 00000025524 12613456020 031537 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.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.config.MessageConstraints; 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 CHUNK_INVALID = Integer.MAX_VALUE; private static final int BUFFER_SIZE = 2048; /** The session input buffer */ private final SessionInputBuffer in; private final CharArrayBuffer buffer; private final MessageConstraints constraints; private int state; /** The chunk size */ private int chunkSize; /** The current position within the current chunk */ private int pos; /** True if we've reached the end of stream */ private boolean eof = false; /** True if this stream is closed */ private boolean closed = false; private Header[] footers = new Header[] {}; /** * Wraps session input stream and reads chunk coded input. * * @param in The session input buffer * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * * @since 4.4 */ public ChunkedInputStream(final SessionInputBuffer in, final MessageConstraints constraints) { super(); this.in = Args.notNull(in, "Session input buffer"); this.pos = 0; this.buffer = new CharArrayBuffer(16); this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; this.state = CHUNK_LEN; } /** * Wraps session input stream and reads chunk coded input. * * @param in The session input buffer */ public ChunkedInputStream(final SessionInputBuffer in) { this(in, null); } @Override public int available() throws IOException { if (this.in instanceof BufferInfo) { final int len = ((BufferInfo) this.in).length(); return Math.min(len, this.chunkSize - this.pos); } else { return 0; } } /** *

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

* *

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

* * @return -1 of the end of the stream has been reached or the next data * byte * @throws IOException in case of an I/O error */ @Override public int read() throws IOException { if (this.closed) { throw new IOException("Attempted read from closed stream."); } if (this.eof) { return -1; } if (state != CHUNK_DATA) { nextChunk(); if (this.eof) { return -1; } } final int b = in.read(); if (b != -1) { pos++; if (pos >= chunkSize) { state = CHUNK_CRLF; } } return b; } /** * Read some bytes from the stream. * @param b The byte array that will hold the contents from the stream. * @param off The offset into the byte array at which bytes will start to be * placed. * @param len the maximum number of bytes that can be returned. * @return The number of bytes returned or -1 if the end of stream has been * reached. * @throws IOException in case of an I/O error */ @Override public int read (final byte[] b, final int off, final int len) throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (eof) { return -1; } if (state != CHUNK_DATA) { nextChunk(); if (eof) { return -1; } } final int bytesRead = in.read(b, off, Math.min(len, chunkSize - pos)); if (bytesRead != -1) { pos += bytesRead; if (pos >= chunkSize) { state = CHUNK_CRLF; } return bytesRead; } else { eof = true; throw new TruncatedChunkException("Truncated chunk " + "( expected size: " + chunkSize + "; actual size: " + pos + ")"); } } /** * Read some bytes from the stream. * @param b The byte array that will hold the contents from the stream. * @return The number of bytes returned or -1 if the end of stream has been * reached. * @throws IOException in case of an I/O error */ @Override public int read (final byte[] b) throws IOException { return read(b, 0, b.length); } /** * Read the next chunk. * @throws IOException in case of an I/O error */ private void nextChunk() throws IOException { if (state == CHUNK_INVALID) { throw new MalformedChunkCodingException("Corrupt data stream"); } try { chunkSize = getChunkSize(); if (chunkSize < 0) { throw new MalformedChunkCodingException("Negative chunk size"); } state = CHUNK_DATA; pos = 0; if (chunkSize == 0) { eof = true; parseTrailerHeaders(); } } catch (MalformedChunkCodingException ex) { state = CHUNK_INVALID; throw ex; } } /** * Expects the stream to start with a chunksize in hex with optional * comments after a semicolon. The line must end with a CRLF: "a3; some * comment\r\n" Positions the stream at the start of the next line. */ private int getChunkSize() throws IOException { final int st = this.state; switch (st) { case CHUNK_CRLF: this.buffer.clear(); final int bytesRead1 = this.in.readLine(this.buffer); if (bytesRead1 == -1) { throw new MalformedChunkCodingException( "CRLF expected at end of chunk"); } if (!this.buffer.isEmpty()) { throw new MalformedChunkCodingException( "Unexpected content at the end of chunk"); } state = CHUNK_LEN; //$FALL-THROUGH$ case CHUNK_LEN: this.buffer.clear(); final int bytesRead2 = this.in.readLine(this.buffer); if (bytesRead2 == -1) { throw new ConnectionClosedException("Premature end of chunk coded message body: " + "closing chunk expected"); } int separator = this.buffer.indexOf(';'); if (separator < 0) { separator = this.buffer.length(); } try { return Integer.parseInt(this.buffer.substringTrimmed(0, separator), 16); } catch (final NumberFormatException e) { throw new MalformedChunkCodingException("Bad chunk header"); } default: throw new IllegalStateException("Inconsistent codec state"); } } /** * Reads and stores the Trailer headers. * @throws IOException in case of an I/O error */ private void parseTrailerHeaders() throws IOException { try { this.footers = AbstractMessageParser.parseHeaders(in, constraints.getMaxHeaderCount(), constraints.getMaxLineLength(), null); } catch (final HttpException ex) { final IOException ioe = new MalformedChunkCodingException("Invalid footer: " + ex.getMessage()); ioe.initCause(ex); throw ioe; } } /** * Upon close, this reads the remainder of the chunked message, * leaving the underlying socket at a position to start reading the * next response without scanning. * @throws IOException in case of an I/O error */ @Override public void close() throws IOException { if (!closed) { try { if (!eof && state != CHUNK_INVALID) { // read and discard the remainder of the message final byte buff[] = new byte[BUFFER_SIZE]; while (read(buff) >= 0) { } } } finally { eof = true; closed = true; } } } public Header[] getFooters() { return this.footers.clone(); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriter.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriter.ja0100644 0000000 0000000 00000004607 12613456020 032424 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code 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.4.4/httpcore/src/main/java/org/apache/http/impl/entity/0040755 0000000 0000000 00000000000 12613456020 026017 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/entity/StrictContentLengthStrategy.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/entity/StrictContentLengthStra0100644 0000000 0000000 00000010761 12613456020 032543 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Content-Length} header * value. *

* This class recognizes "chunked" and "identitiy" transfer-coding only. * * @since 4.0 */ @Immutable public class StrictContentLengthStrategy implements ContentLengthStrategy { public static final StrictContentLengthStrategy INSTANCE = new StrictContentLengthStrategy(); private final int implicitLen; /** * Creates {@code StrictContentLengthStrategy} instance with the given length used per default * when content length is not explicitly specified in the message. * * @param implicitLen implicit content length. * * @since 4.2 */ public StrictContentLengthStrategy(final int implicitLen) { super(); this.implicitLen = implicitLen; } /** * Creates {@code StrictContentLengthStrategy} instance. {@link ContentLengthStrategy#IDENTITY} * is used per default when content length is not explicitly specified in the message. */ public StrictContentLengthStrategy() { this(IDENTITY); } @Override public long determineLength(final HttpMessage message) throws HttpException { Args.notNull(message, "HTTP message"); // Although Transfer-Encoding is specified as a list, in practice // it is either missing or has the single value "chunked". So we // treat it as a single-valued header here. final Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING); if (transferEncodingHeader != null) { final String s = transferEncodingHeader.getValue(); if (HTTP.CHUNK_CODING.equalsIgnoreCase(s)) { if (message.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) { throw new ProtocolException( "Chunked transfer encoding not allowed for " + message.getProtocolVersion()); } return CHUNKED; } else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(s)) { return IDENTITY; } else { throw new ProtocolException( "Unsupported transfer encoding: " + s); } } final Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN); if (contentLengthHeader != null) { final String s = contentLengthHeader.getValue(); try { final long len = Long.parseLong(s); if (len < 0) { throw new ProtocolException("Negative content length: " + s); } return len; } catch (final NumberFormatException e) { throw new ProtocolException("Invalid content length: " + s); } } return this.implicitLen; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/entity/package-info.java0100644 0000000 0000000 00000002407 12613456020 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 * . * */ /** * Default implementations of entity content strategies. */ package org.apache.http.impl.entity; ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/entity/LaxContentLengthStrategy.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/entity/LaxContentLengthStrateg0100644 0000000 0000000 00000011350 12613456020 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.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 {@code Content-Length} * header values. *

* This class recognizes "chunked" and "identitiy" transfer-coding only. * * @since 4.0 */ @Immutable public class LaxContentLengthStrategy implements ContentLengthStrategy { public static final LaxContentLengthStrategy INSTANCE = new LaxContentLengthStrategy(); private final int implicitLen; /** * Creates {@code LaxContentLengthStrategy} instance with the given length used per default * when content length is not explicitly specified in the message. * * @param implicitLen implicit content length. * * @since 4.2 */ public LaxContentLengthStrategy(final int implicitLen) { super(); this.implicitLen = implicitLen; } /** * Creates {@code LaxContentLengthStrategy} instance. {@link ContentLengthStrategy#IDENTITY} * is used per default when content length is not explicitly specified in the message. */ public LaxContentLengthStrategy() { this(IDENTITY); } @Override public long determineLength(final HttpMessage message) throws HttpException { Args.notNull(message, "HTTP message"); final Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING); // We use Transfer-Encoding if present and ignore Content-Length. // RFC2616, 4.4 item number 3 if (transferEncodingHeader != null) { final HeaderElement[] encodings; try { encodings = transferEncodingHeader.getElements(); } catch (final ParseException px) { throw new ProtocolException ("Invalid Transfer-Encoding header value: " + transferEncodingHeader, px); } // The chunked encoding must be the last one applied RFC2616, 14.41 final int len = encodings.length; if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) { return IDENTITY; } else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase( encodings[len - 1].getName()))) { return CHUNKED; } else { return IDENTITY; } } final Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN); if (contentLengthHeader != null) { long contentlen = -1; final Header[] headers = message.getHeaders(HTTP.CONTENT_LEN); for (int i = headers.length - 1; i >= 0; i--) { final Header header = headers[i]; try { contentlen = Long.parseLong(header.getValue()); break; } catch (final NumberFormatException ignore) { } // See if we can have better luck with another header, if present } if (contentlen >= 0) { return contentlen; } else { return IDENTITY; } } return this.implicitLen; } } ././@LongLink0100644 0000000 0000000 00000000170 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.javahttpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/impl/entity/DisallowIdentityContent0100644 0000000 0000000 00000004623 12613456020 032567 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; } @Override public long determineLength(final HttpMessage message) throws HttpException { final long result = this.contentLengthStrategy.determineLength(message); if (result == ContentLengthStrategy.IDENTITY) { throw new ProtocolException("Identity transfer encoding cannot be used"); } return result; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/io/0040755 0000000 0000000 00000000000 12613456022 024153 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/io/HttpTransportMetrics.java0100644 0000000 0000000 00000003011 12613456022 031171 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/io/HttpMessageParserFactory.java0100644 0000000 0000000 00000003005 12613456022 031742 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/io/EofSensor.java0100644 0000000 0000000 00000002520 12613456022 026715 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/io/BufferInfo.java0100644 0000000 0000000 00000003171 12613456022 027042 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/io/HttpMessageParser.java0100644 0000000 0000000 00000003525 12613456022 030421 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/io/SessionOutputBuffer.java0100644 0000000 0000000 00000010260 12613456022 031010 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code len} bytes from the specified byte array * starting at offset {@code off} to this session buffer. *

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

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

* The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param buffer the buffer containing chars of the line. * @exception IOException if an I/O error occurs. */ void writeLine(CharArrayBuffer buffer) throws IOException; /** * Flushes this session buffer and forces any buffered output bytes * to be written out. The general contract of {@code flush} is * that calling it is an indication that, if any bytes previously * written have been buffered by the implementation of the output * stream, such bytes should immediately be written to their * intended destination. * * @exception IOException if an I/O error occurs. */ void flush() throws IOException; /** * Returns {@link HttpTransportMetrics} for this session buffer. * * @return transport metrics. */ HttpTransportMetrics getMetrics(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/io/package-info.java0100644 0000000 0000000 00000002430 12613456022 027336 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/io/HttpMessageWriter.java0100644 0000000 0000000 00000003447 12613456022 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. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/io/HttpMessageWriterFactory.java0100644 0000000 0000000 00000002664 12613456022 031774 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/io/SessionInputBuffer.java0100644 0000000 0000000 00000014403 12613456022 030612 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code len} bytes of data from the session buffer into * an array of bytes. An attempt is made to read as many as * {@code len} bytes, but a smaller number may be read, possibly * zero. The number of bytes actually read is returned as an integer. * *

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

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

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

* The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @return HTTP line as a string * @exception IOException if an I/O error occurs. */ String readLine() throws IOException; /** Blocks until some data becomes available in the session buffer or the * given timeout period in milliseconds elapses. If the timeout value is * {@code 0} this method blocks indefinitely. * * @param timeout in milliseconds. * @return {@code true} if some data is available in the session * buffer or {@code false} otherwise. * @exception IOException if an I/O error occurs. * * @deprecated (4.3) do not use. This function should be provided at the * connection level */ @Deprecated boolean isDataAvailable(int timeout) throws IOException; /** * Returns {@link HttpTransportMetrics} for this session buffer. * * @return transport metrics. */ HttpTransportMetrics getMetrics(); } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/0040755 0000000 0000000 00000000000 12613456022 025060 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/SerializableEntity.java0100644 0000000 0000000 00000007615 12613456022 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.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(); } @Override public InputStream getContent() throws IOException, IllegalStateException { if (this.objSer == null) { createBytes(this.objRef); } return new ByteArrayInputStream(this.objSer); } @Override public long getContentLength() { if (this.objSer == null) { return -1; } else { return this.objSer.length; } } @Override public boolean isRepeatable() { return true; } @Override public boolean isStreaming() { return this.objSer == null; } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); if (this.objSer == null) { final ObjectOutputStream out = new ObjectOutputStream(outstream); out.writeObject(this.objRef); out.flush(); } else { outstream.write(this.objSer); outstream.flush(); } } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/ContentProducer.java0100644 0000000 0000000 00000002777 12613456022 031053 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/entity/BufferedHttpEntity.java0100644 0000000 0000000 00000007411 12613456022 031502 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.HttpEntity; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; /** * 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) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); entity.writeTo(out); out.flush(); this.buffer = out.toByteArray(); } else { this.buffer = null; } } @Override public long getContentLength() { if (this.buffer != null) { return this.buffer.length; } else { return super.getContentLength(); } } @Override public InputStream getContent() throws IOException { if (this.buffer != null) { return new ByteArrayInputStream(this.buffer); } else { return super.getContent(); } } /** * Tells that this entity does not have to be chunked. * * @return {@code false} */ @Override public boolean isChunked() { return (buffer == null) && super.isChunked(); } /** * Tells that this entity is repeatable. * * @return {@code true} */ @Override public boolean isRepeatable() { return true; } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); if (this.buffer != null) { outstream.write(this.buffer); } else { super.writeTo(outstream); } } // non-javadoc, see interface HttpEntity @Override public boolean isStreaming() { return (buffer == null) && super.isStreaming(); } } // class BufferedHttpEntity httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/FileEntity.java0100644 0000000 0000000 00000006762 12613456022 030007 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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"); } @Override public boolean isRepeatable() { return true; } @Override public long getContentLength() { return this.file.length(); } @Override public InputStream getContent() throws IOException { return new FileInputStream(this.file); } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); final InputStream instream = new FileInputStream(this.file); try { final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE]; int l; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } outstream.flush(); } finally { instream.close(); } } /** * Tells that this entity is not streaming. * * @return {@code false} */ @Override public boolean isStreaming() { return false; } @Override public Object clone() throws CloneNotSupportedException { // File instance is considered immutable // No need to make a copy of it return super.clone(); } } // class FileEntity httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/EntityTemplate.java0100644 0000000 0000000 00000004653 12613456022 030700 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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"); } @Override public long getContentLength() { return -1; } @Override public InputStream getContent() throws IOException { final ByteArrayOutputStream buf = new ByteArrayOutputStream(); writeTo(buf); return new ByteArrayInputStream(buf.toByteArray()); } @Override public boolean isRepeatable() { return true; } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); this.contentproducer.writeTo(outstream); } @Override public boolean isStreaming() { return false; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/package-info.java0100644 0000000 0000000 00000002356 12613456022 030252 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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.4.4/httpcore/src/main/java/org/apache/http/entity/ContentLengthStrategy.java0100644 0000000 0000000 00000004103 12613456022 032215 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.4.4/httpcore/src/main/java/org/apache/http/entity/HttpEntityWrapper.java0100644 0000000 0000000 00000006473 12613456022 031407 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 @Override public boolean isRepeatable() { return wrappedEntity.isRepeatable(); } @Override public boolean isChunked() { return wrappedEntity.isChunked(); } @Override public long getContentLength() { return wrappedEntity.getContentLength(); } @Override public Header getContentType() { return wrappedEntity.getContentType(); } @Override public Header getContentEncoding() { return wrappedEntity.getContentEncoding(); } @Override public InputStream getContent() throws IOException { return wrappedEntity.getContent(); } @Override public void writeTo(final OutputStream outstream) throws IOException { wrappedEntity.writeTo(outstream); } @Override public boolean isStreaming() { return wrappedEntity.isStreaming(); } /** * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ @Override @Deprecated public void consumeContent() throws IOException { wrappedEntity.consumeContent(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/BasicHttpEntity.java0100644 0000000 0000000 00000007472 12613456022 031010 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.impl.io.EmptyInputStream; 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; } @Override public long getContentLength() { return this.length; } /** * Obtains the content, once only. * * @return the content, if this is the first call to this method * since {@link #setContent setContent} has been called * * @throws IllegalStateException * if the content has not been provided */ @Override public InputStream getContent() throws IllegalStateException { Asserts.check(this.content != null, "Content has not been provided"); return this.content; } /** * Tells that this entity is not repeatable. * * @return {@code false} */ @Override public boolean isRepeatable() { return false; } /** * Specifies the length of the content. * * @param len the number of bytes in the content, or * a negative number to indicate an unknown length */ public void setContentLength(final long len) { this.length = len; } /** * Specifies the content. * * @param instream the stream to return with the next call to * {@link #getContent getContent} */ public void setContent(final InputStream instream) { this.content = instream; } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); final InputStream instream = getContent(); try { int l; final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE]; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } } finally { instream.close(); } } @Override public boolean isStreaming() { return this.content != null && this.content != EmptyInputStream.INSTANCE; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/AbstractHttpEntity.java0100644 0000000 0000000 00000015156 12613456022 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.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 * {@code null}, {@code null} and {@code false}, respectively. */ protected AbstractHttpEntity() { super(); } /** * Obtains the Content-Type header. * The default implementation returns the value of the * {@link #contentType contentType} attribute. * * @return the Content-Type header, or {@code null} */ @Override public Header getContentType() { return this.contentType; } /** * Obtains the Content-Encoding header. * The default implementation returns the value of the * {@link #contentEncoding contentEncoding} attribute. * * @return the Content-Encoding header, or {@code null} */ @Override public Header getContentEncoding() { return this.contentEncoding; } /** * Obtains the 'chunked' flag. * The default implementation returns the value of the * {@link #chunked chunked} attribute. * * @return the 'chunked' flag */ @Override public boolean isChunked() { return this.chunked; } /** * Specifies the Content-Type header. * The default implementation sets the value of the * {@link #contentType contentType} attribute. * * @param contentType the new Content-Encoding header, or * {@code null} to unset */ public void setContentType(final Header contentType) { this.contentType = contentType; } /** * Specifies the Content-Type header, as a string. * The default implementation calls * {@link #setContentType(Header) setContentType(Header)}. * * @param ctString the new Content-Type header, or * {@code null} to unset */ public void setContentType(final String ctString) { Header h = null; if (ctString != null) { h = new BasicHeader(HTTP.CONTENT_TYPE, ctString); } setContentType(h); } /** * Specifies the Content-Encoding header. * The default implementation sets the value of the * {@link #contentEncoding contentEncoding} attribute. * * @param contentEncoding the new Content-Encoding header, or * {@code null} to unset */ public void setContentEncoding(final Header contentEncoding) { this.contentEncoding = contentEncoding; } /** * Specifies the Content-Encoding header, as a string. * The default implementation calls * {@link #setContentEncoding(Header) setContentEncoding(Header)}. * * @param ceString the new Content-Encoding header, or * {@code null} to unset */ public void setContentEncoding(final String ceString) { Header h = null; if (ceString != null) { h = new BasicHeader(HTTP.CONTENT_ENCODING, ceString); } setContentEncoding(h); } /** * Specifies the 'chunked' flag. *

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

* The default implementation sets the value of the * {@link #chunked chunked} attribute. * * @param b the new 'chunked' flag */ public void setChunked(final boolean b) { this.chunked = b; } /** * The default implementation does not consume anything. * * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(java.io.OutputStream)} which is required to free the resources. */ @Override @Deprecated public void consumeContent() throws IOException { } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append('['); if (contentType != null) { sb.append("Content-Type: "); sb.append(contentType.getValue()); sb.append(','); } if (contentEncoding != null) { sb.append("Content-Encoding: "); sb.append(contentEncoding.getValue()); sb.append(','); } final long len = getContentLength(); if (len >= 0) { sb.append("Content-Length: "); sb.append(len); sb.append(','); } sb.append("Chunked: "); sb.append(chunked); sb.append(']'); return sb.toString(); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/ContentType.java0100644 0000000 0000000 00000037034 12613456022 030203 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; 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.BasicNameValuePair; 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 {@code <">, <;>, <,>} reserved by the HTTP specification. * * @since 4.2 */ @Immutable public final class ContentType implements Serializable { private static final long serialVersionUID = -7768694718232371896L; // constants public static final ContentType APPLICATION_ATOM_XML = create( "application/atom+xml", Consts.ISO_8859_1); public static final ContentType APPLICATION_FORM_URLENCODED = create( "application/x-www-form-urlencoded", Consts.ISO_8859_1); public static final ContentType APPLICATION_JSON = create( "application/json", Consts.UTF_8); public static final ContentType APPLICATION_OCTET_STREAM = create( "application/octet-stream", (Charset) null); public static final ContentType APPLICATION_SVG_XML = create( "application/svg+xml", Consts.ISO_8859_1); public static final ContentType APPLICATION_XHTML_XML = create( "application/xhtml+xml", Consts.ISO_8859_1); public static final ContentType APPLICATION_XML = create( "application/xml", Consts.ISO_8859_1); public static final ContentType MULTIPART_FORM_DATA = create( "multipart/form-data", Consts.ISO_8859_1); public static final ContentType TEXT_HTML = create( "text/html", Consts.ISO_8859_1); public static final ContentType TEXT_PLAIN = create( "text/plain", Consts.ISO_8859_1); public static final ContentType TEXT_XML = create( "text/xml", Consts.ISO_8859_1); public static final ContentType WILDCARD = create( "*/*", (Charset) null); // defaults public static final ContentType DEFAULT_TEXT = TEXT_PLAIN; public static final ContentType DEFAULT_BINARY = APPLICATION_OCTET_STREAM; private final String mimeType; private final Charset charset; private final NameValuePair[] params; ContentType( final String mimeType, final Charset charset) { this.mimeType = mimeType; this.charset = charset; this.params = null; } ContentType( final String mimeType, final Charset charset, final NameValuePair[] params) { this.mimeType = mimeType; this.charset = charset; this.params = params; } public String getMimeType() { return this.mimeType; } public Charset getCharset() { return this.charset; } /** * @since 4.3 */ public String getParameter(final String name) { Args.notEmpty(name, "Parameter name"); if (this.params == null) { return null; } for (final NameValuePair param: this.params) { if (param.getName().equalsIgnoreCase(name)) { return param.getValue(); } } return null; } /** * Generates textual representation of this content type which can be used as the value * of a {@code Content-Type} header. */ @Override public String toString() { final CharArrayBuffer buf = new CharArrayBuffer(64); buf.append(this.mimeType); if (this.params != null) { buf.append("; "); BasicHeaderValueFormatter.INSTANCE.formatParameters(buf, this.params, false); } else if (this.charset != null) { buf.append("; charset="); buf.append(this.charset.name()); } return buf.toString(); } private static boolean valid(final String s) { for (int i = 0; i < s.length(); i++) { final char ch = s.charAt(i); if (ch == '"' || ch == ',' || ch == ';') { return false; } } return true; } /** * Creates a new instance of {@link ContentType}. * * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain * characters {@code <">, <;>, <,>} reserved by the HTTP specification. * @param charset charset. * @return content type */ public static ContentType create(final String mimeType, final Charset charset) { final String type = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.ROOT); Args.check(valid(type), "MIME type may not contain reserved characters"); return new ContentType(type, charset); } /** * Creates a new instance of {@link ContentType} without a charset. * * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain * characters {@code <">, <;>, <,>} reserved by the HTTP specification. * @return content type */ public static ContentType create(final String mimeType) { return new ContentType(mimeType, (Charset) null); } /** * Creates a new instance of {@link ContentType}. * * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain * characters {@code <">, <;>, <,>} reserved by the HTTP specification. * @param charset charset. It may not contain characters {@code <">, <;>, <,>} reserved by the HTTP * specification. This parameter is optional. * @return content type * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public static ContentType create( final String mimeType, final String charset) throws UnsupportedCharsetException { return create(mimeType, !TextUtils.isBlank(charset) ? Charset.forName(charset) : null); } private static ContentType create(final HeaderElement helem, final boolean strict) { return create(helem.getName(), helem.getParameters(), strict); } private static ContentType create(final String mimeType, final NameValuePair[] params, final boolean strict) { Charset charset = null; for (final NameValuePair param: params) { if (param.getName().equalsIgnoreCase("charset")) { final String s = param.getValue(); if (!TextUtils.isBlank(s)) { try { charset = Charset.forName(s); } catch (UnsupportedCharsetException ex) { if (strict) { throw ex; } } } break; } } return new ContentType(mimeType, charset, params != null && params.length > 0 ? params : null); } /** * Creates a new instance of {@link ContentType} with the given parameters. * * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain * characters {@code <">, <;>, <,>} reserved by the HTTP specification. * @param params parameters. * @return content type * * @since 4.4 */ public static ContentType create( final String mimeType, final NameValuePair... params) throws UnsupportedCharsetException { final String type = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.ROOT); Args.check(valid(type), "MIME type may not contain reserved characters"); return create(mimeType, params, true); } /** * Parses textual representation of {@code Content-Type} value. * * @param s text * @return content type * @throws ParseException if the given text does not represent a valid * {@code Content-Type} value. * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public static ContentType parse( final String s) throws ParseException, UnsupportedCharsetException { Args.notNull(s, "Content type"); final CharArrayBuffer buf = new CharArrayBuffer(s.length()); buf.append(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(buf, cursor); if (elements.length > 0) { return create(elements[0], true); } else { throw new ParseException("Invalid content type: " + s); } } /** * Extracts {@code Content-Type} value from {@link HttpEntity} exactly as * specified by the {@code Content-Type} header of the entity. Returns {@code null} * if not specified. * * @param entity HTTP entity * @return content type * @throws ParseException if the given text does not represent a valid * {@code Content-Type} value. * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public static ContentType get( final HttpEntity entity) throws ParseException, UnsupportedCharsetException { if (entity == null) { return null; } final Header header = entity.getContentType(); if (header != null) { final HeaderElement[] elements = header.getElements(); if (elements.length > 0) { return create(elements[0], true); } } return null; } /** * Extracts {@code Content-Type} value from {@link HttpEntity}. Returns {@code null} * if not specified or incorrect (could not be parsed).. * * @param entity HTTP entity * @return content type * * @since 4.4 * */ public static ContentType getLenient(final HttpEntity entity) { if (entity == null) { return null; } final Header header = entity.getContentType(); if (header != null) { try { final HeaderElement[] elements = header.getElements(); if (elements.length > 0) { return create(elements[0], false); } } catch (ParseException ex) { return null; } } return null; } /** * Extracts {@code Content-Type} value from {@link HttpEntity} or returns the default value * {@link #DEFAULT_TEXT} if not explicitly specified. * * @param entity HTTP entity * @return content type * @throws ParseException if the given text does not represent a valid * {@code Content-Type} value. * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public static ContentType getOrDefault( final HttpEntity entity) throws ParseException, UnsupportedCharsetException { final ContentType contentType = get(entity); return contentType != null ? contentType : DEFAULT_TEXT; } /** * Extracts {@code Content-Type} value from {@link HttpEntity} or returns the default value * {@link #DEFAULT_TEXT} if not explicitly specified or incorrect (could not be parsed). * * @param entity HTTP entity * @return content type * * @since 4.4 */ public static ContentType getLenientOrDefault( final HttpEntity entity) throws ParseException, UnsupportedCharsetException { final ContentType contentType = get(entity); return contentType != null ? contentType : DEFAULT_TEXT; } /** * Creates a new instance with this MIME type and the given Charset. * * @param charset charset * @return a new instance with this MIME type and the given Charset. * @since 4.3 */ public ContentType withCharset(final Charset charset) { return create(this.getMimeType(), charset); } /** * Creates a new instance with this MIME type and the given Charset name. * * @param charset name * @return a new instance with this MIME type and the given Charset name. * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine * @since 4.3 */ public ContentType withCharset(final String charset) { return create(this.getMimeType(), charset); } /** * Creates a new instance with this MIME type and the given parameters. * * @param params * @return a new instance with this MIME type and the given parameters. * @since 4.4 */ public ContentType withParameters( final NameValuePair... params) throws UnsupportedCharsetException { if (params.length == 0) { return this; } final Map paramMap = new LinkedHashMap(); if (this.params != null) { for (NameValuePair param: this.params) { paramMap.put(param.getName(), param.getValue()); } } for (NameValuePair param: params) { paramMap.put(param.getName(), param.getValue()); } final List newParams = new ArrayList(paramMap.size() + 1); if (this.charset != null && !paramMap.containsKey("charset")) { newParams.add(new BasicNameValuePair("charset", this.charset.name())); } for (Map.Entry entry: paramMap.entrySet()) { newParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return create(this.getMimeType(), newParams.toArray(new NameValuePair[newParams.size()]), true); } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/ByteArrayEntity.java0100644 0000000 0000000 00000007475 12613456022 031034 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } @Override public boolean isRepeatable() { return true; } @Override public long getContentLength() { return this.len; } @Override public InputStream getContent() { return new ByteArrayInputStream(this.b, this.off, this.len); } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); outstream.write(this.b, this.off, this.len); outstream.flush(); } /** * Tells that this entity is not streaming. * * @return {@code false} */ @Override public boolean isStreaming() { return false; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } // class ByteArrayEntity httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/InputStreamEntity.java0100644 0000000 0000000 00000012216 12613456022 031372 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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()); } } @Override public boolean isRepeatable() { return false; } /** * @return the content length or {@code -1} if unknown */ @Override public long getContentLength() { return this.length; } @Override public InputStream getContent() throws IOException { return this.content; } /** * Writes bytes from the {@code InputStream} this entity was constructed * with to an {@code OutputStream}. The content length * determines how many bytes are written. If the length is unknown ({@code -1}), the * stream will be completely consumed (to the end of the stream). * */ @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); final InputStream instream = this.content; try { final byte[] buffer = new byte[OUTPUT_BUFFER_SIZE]; int l; if (this.length < 0) { // consume until EOF while ((l = instream.read(buffer)) != -1) { outstream.write(buffer, 0, l); } } else { // consume no more than length long remaining = this.length; while (remaining > 0) { l = instream.read(buffer, 0, (int)Math.min(OUTPUT_BUFFER_SIZE, remaining)); if (l == -1) { break; } outstream.write(buffer, 0, l); remaining -= l; } } } finally { instream.close(); } } @Override public boolean isStreaming() { return true; } } httpcomponents-core-4.4.4/httpcore/src/main/java/org/apache/http/entity/StringEntity.java0100644 0000000 0000000 00000015334 12613456022 030371 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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; } this.content = string.getBytes(charset); if (contentType != null) { setContentType(contentType.toString()); } } /** * Creates a StringEntity with the specified content, MIME type and charset * * @param string content to be used. Not {@code null}. * @param mimeType MIME type to be used. May be {@code null}, in which case the default * is {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain" * @param charset character set to be used. May be {@code null}, in which case the default * is {@link HTTP#DEF_CONTENT_CHARSET} i.e. "ISO-8859-1" * @throws UnsupportedEncodingException If the named charset is not supported. * * @since 4.1 * @throws IllegalArgumentException if the string parameter is null * * @deprecated (4.1.3) use {@link #StringEntity(String, ContentType)} */ @Deprecated public StringEntity( final String string, final String mimeType, final String charset) throws UnsupportedEncodingException { super(); Args.notNull(string, "Source string"); final String mt = mimeType != null ? mimeType : HTTP.PLAIN_TEXT_TYPE; final String cs = charset != null ? charset :HTTP.DEFAULT_CONTENT_CHARSET; this.content = string.getBytes(cs); setContentType(mt + HTTP.CHARSET_PARAM + cs); } /** * Creates a StringEntity with the specified content and charset. The MIME type defaults * to "text/plain". * * @param string content to be used. Not {@code null}. * @param charset character set to be used. May be {@code null}, in which case the default * is {@link HTTP#DEF_CONTENT_CHARSET} is assumed * * @throws IllegalArgumentException if the string parameter is null * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public StringEntity(final String string, final String charset) throws UnsupportedCharsetException { this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset)); } /** * Creates a StringEntity with the specified content and charset. The MIME type defaults * to "text/plain". * * @param string content to be used. Not {@code null}. * @param charset character set to be used. May be {@code null}, in which case the default * is {@link HTTP#DEF_CONTENT_CHARSET} is assumed * * @throws IllegalArgumentException if the string parameter is null * * @since 4.2 */ public StringEntity(final String string, final Charset charset) { this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset)); } /** * Creates a StringEntity with the specified content. The content type defaults to * {@link ContentType#TEXT_PLAIN}. * * @param string content to be used. Not {@code null}. * * @throws IllegalArgumentException if the string parameter is null * @throws UnsupportedEncodingException if the default HTTP charset is not supported. */ public StringEntity(final String string) throws UnsupportedEncodingException { this(string, ContentType.DEFAULT_TEXT); } @Override public boolean isRepeatable() { return true; } @Override public long getContentLength() { return this.content.length; } @Override public InputStream getContent() throws IOException { return new ByteArrayInputStream(this.content); } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); outstream.write(this.content); outstream.flush(); } /** * Tells that this entity is not streaming. * * @return {@code false} */ @Override public boolean isStreaming() { return false; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } // class StringEntity httpcomponents-core-4.4.4/httpcore/src/main/appended-resources/0040755 0000000 0000000 00000000000 12613456022 023424 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/appended-resources/META-INF/0040755 0000000 0000000 00000000000 12613456022 024564 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/appended-resources/META-INF/NOTICE0100644 0000000 0000000 00000000210 12613456022 025456 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.4.4/httpcore/src/main/appended-resources/META-INF/LICENSE0100644 0000000 0000000 00000026564 12613456022 025603 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.4.4/httpcore/src/main/resources/0040755 0000000 0000000 00000000000 12613456022 021646 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/resources/org/0040755 0000000 0000000 00000000000 12613456022 022435 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/resources/org/apache/0040755 0000000 0000000 00000000000 12613456022 023656 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/resources/org/apache/http/0040755 0000000 0000000 00000000000 12613456022 024635 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/resources/org/apache/http/version.properties0100644 0000000 0000000 00000001620 12613456022 030434 0ustar000000000 0000000 # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT 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.4.4/httpcore/src/main/java-deprecated/0040755 0000000 0000000 00000000000 12613456016 022656 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/0040755 0000000 0000000 00000000000 12613456016 023445 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/0040755 0000000 0000000 00000000000 12613456016 024666 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/0040755 0000000 0000000 00000000000 12613456016 025645 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/0040755 0000000 0000000 00000000000 12613456016 027130 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpAbstractParamBean.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpAbstractParam0100644 0000000 0000000 00000003160 12613456016 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.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"); } } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpProtocolParams.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpProtocolParam0100644 0000000 0000000 00000021004 12613456016 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 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 {@code US-ASCII}. * * @param params HTTP parameters. * @return HTTP element charset. */ public static String getHttpElementCharset(final HttpParams params) { Args.notNull(params, "HTTP parameters"); String charset = (String) params.getParameter (CoreProtocolPNames.HTTP_ELEMENT_CHARSET); if (charset == null) { charset = HTTP.DEF_PROTOCOL_CHARSET.name(); } return charset; } /** * Sets value of the {@link CoreProtocolPNames#HTTP_ELEMENT_CHARSET} parameter. * * @param params HTTP parameters. * @param charset HTTP element charset. */ public static void setHttpElementCharset(final HttpParams params, final String charset) { Args.notNull(params, "HTTP parameters"); params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, charset); } /** * Obtains value of the {@link CoreProtocolPNames#HTTP_CONTENT_CHARSET} parameter. * If not set, defaults to {@code ISO-8859-1}. * * @param params HTTP parameters. * @return HTTP content charset. */ public static String getContentCharset(final HttpParams params) { Args.notNull(params, "HTTP parameters"); String charset = (String) params.getParameter (CoreProtocolPNames.HTTP_CONTENT_CHARSET); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET.name(); } return charset; } /** * Sets value of the {@link CoreProtocolPNames#HTTP_CONTENT_CHARSET} parameter. * * @param params HTTP parameters. * @param charset HTTP content charset. */ public static void setContentCharset(final HttpParams params, final String charset) { Args.notNull(params, "HTTP parameters"); params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset); } /** * Obtains value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter. * If not set, defaults to {@link HttpVersion#HTTP_1_1}. * * @param params HTTP parameters. * @return HTTP protocol version. */ public static ProtocolVersion getVersion(final HttpParams params) { Args.notNull(params, "HTTP parameters"); final Object param = params.getParameter (CoreProtocolPNames.PROTOCOL_VERSION); if (param == null) { return HttpVersion.HTTP_1_1; } return (ProtocolVersion)param; } /** * Sets value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter. * * @param params HTTP parameters. * @param version HTTP protocol version. */ public static void setVersion(final HttpParams params, final ProtocolVersion version) { Args.notNull(params, "HTTP parameters"); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, version); } /** * Obtains value of the {@link CoreProtocolPNames#USER_AGENT} parameter. * If not set, returns {@code null}. * * @param params HTTP parameters. * @return User agent string. */ public static String getUserAgent(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return (String) params.getParameter(CoreProtocolPNames.USER_AGENT); } /** * Sets value of the {@link CoreProtocolPNames#USER_AGENT} parameter. * * @param params HTTP parameters. * @param useragent User agent string. */ public static void setUserAgent(final HttpParams params, final String useragent) { Args.notNull(params, "HTTP parameters"); params.setParameter(CoreProtocolPNames.USER_AGENT, useragent); } /** * Obtains value of the {@link CoreProtocolPNames#USE_EXPECT_CONTINUE} parameter. * If not set, returns {@code false}. * * @param params HTTP parameters. * @return User agent string. */ public static boolean useExpectContinue(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); } /** * Sets value of the {@link CoreProtocolPNames#USE_EXPECT_CONTINUE} parameter. * * @param params HTTP parameters. * @param b expect-continue flag. */ public static void setUseExpectContinue(final HttpParams params, final boolean b) { Args.notNull(params, "HTTP parameters"); params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, b); } /** * Obtains value of the {@link CoreProtocolPNames#HTTP_MALFORMED_INPUT_ACTION} parameter. * @param params HTTP parameters. * @return Action to perform upon receiving a malformed input * * @since 4.2 */ public static CodingErrorAction getMalformedInputAction(final HttpParams params) { Args.notNull(params, "HTTP parameters"); final Object param = params.getParameter(CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION); if (param == null) { // the default CodingErrorAction return CodingErrorAction.REPORT; } return (CodingErrorAction) param; } /** * Sets value of the {@link CoreProtocolPNames#HTTP_MALFORMED_INPUT_ACTION} parameter. * @param params HTTP parameters * @param action action to perform on malformed inputs * * @since 4.2 */ public static void setMalformedInputAction(final HttpParams params, final CodingErrorAction action) { Args.notNull(params, "HTTP parameters"); params.setParameter(CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION, action); } /** * Obtains the value of the {@link CoreProtocolPNames#HTTP_UNMAPPABLE_INPUT_ACTION} parameter. * @param params HTTP parameters * @return Action to perform upon receiving a unmapped input * * @since 4.2 */ public static CodingErrorAction getUnmappableInputAction(final HttpParams params) { Args.notNull(params, "HTTP parameters"); final Object param = params.getParameter(CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION); if (param == null) { // the default CodingErrorAction return CodingErrorAction.REPORT; } return (CodingErrorAction) param; } /** * Sets the value of the {@link CoreProtocolPNames#HTTP_UNMAPPABLE_INPUT_ACTION} parameter. * @param params HTTP parameters * @param action action to perform on un mappable inputs * * @since 4.2 */ public static void setUnmappableInputAction(final HttpParams params, final CodingErrorAction action) { Args.notNull(params, "HTTP parameters"); params.setParameter(CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION, action); } } ././@LongLink0100644 0000000 0000000 00000000160 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpConnectionParamBean.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpConnectionPar0100644 0000000 0000000 00000004762 12613456016 032463 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/DefaultedHttpParams.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/DefaultedHttpPara0100644 0000000 0000000 00000012704 12613456016 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.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<String> * @since 4.2 * @throws UnsupportedOperationException if either the local or default HttpParams instances do not implement HttpParamsNames */ @Override public Set getNames() { final Set combined = new HashSet(getNames(defaults)); combined.addAll(getNames(this.local)); return combined ; } /** * Returns the current set of defaults names. * * Changes to the underlying HttpParams are not reflected * in the set - it is a snapshot. * * @return the names, as a Set<String> * @since 4.2 * @throws UnsupportedOperationException if the default HttpParams instance does not implement HttpParamsNames */ public Set getDefaultNames() { return new HashSet(getNames(this.defaults)); } /** * Returns the current set of local names. * * Changes to the underlying HttpParams are not reflected * in the set - it is a snapshot. * * @return the names, as a Set<String> * @since 4.2 * @throws UnsupportedOperationException if the local HttpParams instance does not implement HttpParamsNames */ public Set getLocalNames() { return new HashSet(getNames(this.local)); } // Helper method private Set getNames(final HttpParams params) { if (params instanceof HttpParamsNames) { return ((HttpParamsNames) params).getNames(); } throw new UnsupportedOperationException("HttpParams instance does not implement HttpParamsNames"); } } ././@LongLink0100644 0000000 0000000 00000000154 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/SyncBasicHttpParams.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/SyncBasicHttpPara0100644 0000000 0000000 00000005270 12613456016 032376 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpProtocolParamBean.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpProtocolParam0100644 0000000 0000000 00000004612 12613456016 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.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 00000000155 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpConnectionParams.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/params/HttpConnectionPar0100644 0000000 0000000 00000020316 12613456016 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.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 {@code 0}. * * @param params HTTP parameters. * @return SO_TIMEOUT. */ public static int getSoTimeout(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0); } /** * Sets value of the {@link CoreConnectionPNames#SO_TIMEOUT} parameter. * * @param params HTTP parameters. * @param timeout SO_TIMEOUT. */ public static void setSoTimeout(final HttpParams params, final int timeout) { Args.notNull(params, "HTTP parameters"); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } /** * Obtains value of the {@link CoreConnectionPNames#SO_REUSEADDR} parameter. * If not set, defaults to {@code false}. * * @param params HTTP parameters. * @return SO_REUSEADDR. * * @since 4.1 */ public static boolean getSoReuseaddr(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, false); } /** * Sets value of the {@link CoreConnectionPNames#SO_REUSEADDR} parameter. * * @param params HTTP parameters. * @param reuseaddr SO_REUSEADDR. * * @since 4.1 */ public static void setSoReuseaddr(final HttpParams params, final boolean reuseaddr) { Args.notNull(params, "HTTP parameters"); params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, reuseaddr); } /** * Obtains value of the {@link CoreConnectionPNames#TCP_NODELAY} parameter. * If not set, defaults to {@code true}. * * @param params HTTP parameters. * @return Nagle's algorithm flag */ public static boolean getTcpNoDelay(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); } /** * Sets value of the {@link CoreConnectionPNames#TCP_NODELAY} parameter. * * @param params HTTP parameters. * @param value Nagle's algorithm flag */ public static void setTcpNoDelay(final HttpParams params, final boolean value) { Args.notNull(params, "HTTP parameters"); params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, value); } /** * Obtains value of the {@link CoreConnectionPNames#SOCKET_BUFFER_SIZE} * parameter. If not set, defaults to {@code -1}. * * @param params HTTP parameters. * @return socket buffer size */ public static int getSocketBufferSize(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1); } /** * Sets value of the {@link CoreConnectionPNames#SOCKET_BUFFER_SIZE} * parameter. * * @param params HTTP parameters. * @param size socket buffer size */ public static void setSocketBufferSize(final HttpParams params, final int size) { Args.notNull(params, "HTTP parameters"); params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, size); } /** * Obtains value of the {@link CoreConnectionPNames#SO_LINGER} parameter. * If not set, defaults to {@code -1}. * * @param params HTTP parameters. * @return SO_LINGER. */ public static int getLinger(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1); } /** * Sets value of the {@link CoreConnectionPNames#SO_LINGER} parameter. * * @param params HTTP parameters. * @param value SO_LINGER. */ public static void setLinger(final HttpParams params, final int value) { Args.notNull(params, "HTTP parameters"); params.setIntParameter(CoreConnectionPNames.SO_LINGER, value); } /** * Obtains value of the {@link CoreConnectionPNames#CONNECTION_TIMEOUT} * parameter. If not set, defaults to {@code 0}. * * @param params HTTP parameters. * @return connect timeout. */ public static int getConnectionTimeout(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0); } /** * Sets value of the {@link CoreConnectionPNames#CONNECTION_TIMEOUT} * parameter. * * @param params HTTP parameters. * @param timeout connect timeout. */ public static void setConnectionTimeout(final HttpParams params, final int timeout) { Args.notNull(params, "HTTP parameters"); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); } /** * Obtains value of the {@link CoreConnectionPNames#STALE_CONNECTION_CHECK} * parameter. If not set, defaults to {@code true}. * * @param params HTTP parameters. * @return stale connection check flag. */ public static boolean isStaleCheckingEnabled(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true); } /** * Sets value of the {@link CoreConnectionPNames#STALE_CONNECTION_CHECK} * parameter. * * @param params HTTP parameters. * @param value stale connection check flag. */ public static void setStaleCheckingEnabled(final HttpParams params, final boolean value) { Args.notNull(params, "HTTP parameters"); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, value); } /** * Obtains value of the {@link CoreConnectionPNames#SO_KEEPALIVE} parameter. * If not set, defaults to {@code false}. * * @param params HTTP parameters. * @return SO_KEEPALIVE. * * @since 4.2 */ public static boolean getSoKeepalive(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false); } /** * Sets value of the {@link CoreConnectionPNames#SO_KEEPALIVE} parameter. * * @param params HTTP parameters. * @param enableKeepalive SO_KEEPALIVE. * * @since 4.2 */ public static void setSoKeepalive(final HttpParams params, final boolean enableKeepalive) { Args.notNull(params, "HTTP parameters"); params.setBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, enableKeepalive); } } httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/0040755 0000000 0000000 00000000000 12613456016 027506 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000155 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/BasicHttpProcessor.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/BasicHttpProces0100644 0000000 0000000 00000020251 12613456016 032463 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/DefaultedHttpContext.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/DefaultedHttpCo0100644 0000000 0000000 00000005334 12613456016 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.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 00000000157 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/SyncBasicHttpContext.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/SyncBasicHttpCo0100644 0000000 0000000 00000004167 12613456016 032436 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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(); } } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/ExecutionContext.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/ExecutionContex0100644 0000000 0000000 00000005277 12613456016 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; /** * {@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 00000000165 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/HttpRequestHandlerRegistry.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/protocol/HttpRequestHand0100644 0000000 0000000 00000006717 12613456016 032524 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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: *

    *
  • {@code *}
  • *
  • {@code *<uri>}
  • *
  • {@code <uri>*}
  • *
*
* This class can be used to resolve an instance of * {@link HttpRequestHandler} matching a particular request URI. Usually the * resolved request handler will be used to process the request with the * specified request URI. * * @since 4.0 * @deprecated (4.3) use {@link UriHttpRequestHandlerMapper} */ @ThreadSafe // provided injected dependencies are thread-safe @Deprecated public class HttpRequestHandlerRegistry implements HttpRequestHandlerResolver { private final UriPatternMatcher matcher; public HttpRequestHandlerRegistry() { matcher = new UriPatternMatcher(); } /** * Registers the given {@link HttpRequestHandler} as a handler for URIs * matching the given pattern. * * @param pattern the pattern to register the handler for. * @param handler the handler. */ public void register(final String pattern, final HttpRequestHandler handler) { Args.notNull(pattern, "URI request pattern"); Args.notNull(handler, "Request handler"); matcher.register(pattern, handler); } /** * Removes registered handler, if exists, for the given pattern. * * @param pattern the pattern to unregister the handler for. */ public void unregister(final String pattern) { matcher.unregister(pattern); } /** * Sets handlers from the given map. * @param map the map containing handlers keyed by their URI patterns. */ public void setHandlers(final Map map) { matcher.setObjects(map); } /** * Get the handler map. * @return The map of handlers and their associated URI patterns. * * @since 4.2 */ public Map getHandlers() { return matcher.getObjects(); } public HttpRequestHandler lookup(final String requestURI) { return matcher.lookup(requestURI); } } httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/util/0040755 0000000 0000000 00000000000 12613456016 026622 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/util/ExceptionUtils.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/util/ExceptionUtils.java0100644 0000000 0000000 00000005441 12613456016 032445 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code Method} allowing access to * {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable}, * or {@code null} if the method * does not exist. * * @return A {@code Method} for {@code Throwable.initCause}, or * {@code null} if unavailable. */ static private Method getInitCauseMethod() { try { final Class[] paramsClasses = new Class[] { Throwable.class }; return Throwable.class.getMethod("initCause", paramsClasses); } catch (final NoSuchMethodException e) { return null; } } /** * If we're running on JDK 1.4 or later, initialize the cause for the given throwable. * * @param throwable The throwable. * @param cause The cause of the throwable. */ public static void initCause(final Throwable throwable, final Throwable cause) { if (INIT_CAUSE_METHOD != null) { try { INIT_CAUSE_METHOD.invoke(throwable, cause); } catch (final Exception e) { // Well, with no logging, the only option is to munch the exception } } } private ExceptionUtils() { } } httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/0040755 0000000 0000000 00000000000 12613456016 026606 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000163 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/AbstractHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/AbstractHttpServerC0100644 0000000 0000000 00000026562 12613456016 032436 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/SocketHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/SocketHttpServerCon0100644 0000000 0000000 00000021664 12613456016 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; 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 {@code true}. * * @param socket the socket. * @param params HTTP parameters. * @throws IOException in case of an I/O error. */ protected void bind(final Socket socket, final HttpParams params) throws IOException { Args.notNull(socket, "Socket"); Args.notNull(params, "HTTP parameters"); this.socket = socket; final int buffersize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1); init( createSessionInputBuffer(socket, buffersize, params), createSessionOutputBuffer(socket, buffersize, params), params); this.open = true; } protected Socket getSocket() { return this.socket; } public boolean isOpen() { return this.open; } public InetAddress getLocalAddress() { if (this.socket != null) { return this.socket.getLocalAddress(); } else { return null; } } public int getLocalPort() { if (this.socket != null) { return this.socket.getLocalPort(); } else { return -1; } } public InetAddress getRemoteAddress() { if (this.socket != null) { return this.socket.getInetAddress(); } else { return null; } } public int getRemotePort() { if (this.socket != null) { return this.socket.getPort(); } else { return -1; } } public void setSocketTimeout(final int timeout) { assertOpen(); if (this.socket != null) { try { this.socket.setSoTimeout(timeout); } catch (final SocketException ignore) { // It is not quite clear from the Sun's documentation if there are any // other legitimate cases for a socket exception to be thrown when setting // SO_TIMEOUT besides the socket being already closed } } } public int getSocketTimeout() { if (this.socket != null) { try { return this.socket.getSoTimeout(); } catch (final SocketException ignore) { return -1; } } else { return -1; } } public void shutdown() throws IOException { this.open = false; final Socket tmpsocket = this.socket; if (tmpsocket != null) { tmpsocket.close(); } } public void close() throws IOException { if (!this.open) { return; } this.open = false; this.open = false; final Socket sock = this.socket; try { doFlush(); try { try { sock.shutdownOutput(); } catch (final IOException ignore) { } try { sock.shutdownInput(); } catch (final IOException ignore) { } } catch (final UnsupportedOperationException ignore) { // if one isn't supported, the other one isn't either } } finally { sock.close(); } } private static void formatAddress(final StringBuilder buffer, final SocketAddress socketAddress) { if (socketAddress instanceof InetSocketAddress) { final InetSocketAddress addr = ((InetSocketAddress) socketAddress); buffer.append(addr.getAddress() != null ? addr.getAddress().getHostAddress() : addr.getAddress()) .append(':') .append(addr.getPort()); } else { buffer.append(socketAddress); } } @Override public String toString() { if (this.socket != null) { final StringBuilder buffer = new StringBuilder(); final SocketAddress remoteAddress = this.socket.getRemoteSocketAddress(); final SocketAddress localAddress = this.socket.getLocalSocketAddress(); if (remoteAddress != null && localAddress != null) { formatAddress(buffer, localAddress); buffer.append("<->"); formatAddress(buffer, remoteAddress); } return buffer.toString(); } else { return super.toString(); } } } ././@LongLink0100644 0000000 0000000 00000000162 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/DefaultHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/DefaultHttpServerCo0100644 0000000 0000000 00000005026 12613456016 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.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 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/AbstractHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/AbstractHttpClientC0100644 0000000 0000000 00000027370 12613456016 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.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; } } ././@LongLink0100644 0000000 0000000 00000000162 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/DefaultHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/DefaultHttpClientCo0100644 0000000 0000000 00000004726 12613456016 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.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 00000000161 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/SocketHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/SocketHttpClientCon0100644 0000000 0000000 00000022370 12613456016 032421 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code true}. * * @param socket the socket. * @param params HTTP parameters. * @throws IOException in case of an I/O error. */ protected void bind( final Socket socket, final HttpParams params) throws IOException { Args.notNull(socket, "Socket"); Args.notNull(params, "HTTP parameters"); this.socket = socket; final int buffersize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1); init( createSessionInputBuffer(socket, buffersize, params), createSessionOutputBuffer(socket, buffersize, params), params); this.open = true; } public boolean isOpen() { return this.open; } protected Socket getSocket() { return this.socket; } public InetAddress getLocalAddress() { if (this.socket != null) { return this.socket.getLocalAddress(); } else { return null; } } public int getLocalPort() { if (this.socket != null) { return this.socket.getLocalPort(); } else { return -1; } } public InetAddress getRemoteAddress() { if (this.socket != null) { return this.socket.getInetAddress(); } else { return null; } } public int getRemotePort() { if (this.socket != null) { return this.socket.getPort(); } else { return -1; } } public void setSocketTimeout(final int timeout) { assertOpen(); if (this.socket != null) { try { this.socket.setSoTimeout(timeout); } catch (final SocketException ignore) { // It is not quite clear from the Sun's documentation if there are any // other legitimate cases for a socket exception to be thrown when setting // SO_TIMEOUT besides the socket being already closed } } } public int getSocketTimeout() { if (this.socket != null) { try { return this.socket.getSoTimeout(); } catch (final SocketException ignore) { return -1; } } else { return -1; } } public void shutdown() throws IOException { this.open = false; final Socket tmpsocket = this.socket; if (tmpsocket != null) { tmpsocket.close(); } } public void close() throws IOException { if (!this.open) { return; } this.open = false; final Socket sock = this.socket; try { doFlush(); try { try { sock.shutdownOutput(); } catch (final IOException ignore) { } try { sock.shutdownInput(); } catch (final IOException ignore) { } } catch (final UnsupportedOperationException ignore) { // if one isn't supported, the other one isn't either } } finally { sock.close(); } } private static void formatAddress(final StringBuilder buffer, final SocketAddress socketAddress) { if (socketAddress instanceof InetSocketAddress) { final InetSocketAddress addr = ((InetSocketAddress) socketAddress); buffer.append(addr.getAddress() != null ? addr.getAddress().getHostAddress() : addr.getAddress()) .append(':') .append(addr.getPort()); } else { buffer.append(socketAddress); } } @Override public String toString() { if (this.socket != null) { final StringBuilder buffer = new StringBuilder(); final SocketAddress remoteAddress = this.socket.getRemoteSocketAddress(); final SocketAddress localAddress = this.socket.getLocalSocketAddress(); if (remoteAddress != null && localAddress != null) { formatAddress(buffer, localAddress); buffer.append("<->"); formatAddress(buffer, remoteAddress); } return buffer.toString(); } else { return super.toString(); } } } httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/0040755 0000000 0000000 00000000000 12613456016 027215 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000154 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpResponseParser.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpResponsePars0100644 0000000 0000000 00000007341 12613456016 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.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 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpRequestWriter.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpRequestWrite0100644 0000000 0000000 00000004260 12613456016 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 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); } } ././@LongLink0100644 0000000 0000000 00000000154 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpResponseWriter.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpResponseWrit0100644 0000000 0000000 00000004267 12613456016 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.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 00000000164 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/AbstractSessionInputBuffer.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/AbstractSessionI0100644 0000000 0000000 00000033620 12613456016 032361 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code -1} is returned. This method blocks until input * data is available, end of file is detected, or an exception is thrown. *

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

* This method treats a lone LF as a valid line delimiters in addition * to CR-LF required by the HTTP specification. * * @return HTTP line as a string * @exception IOException if an I/O error occurs. */ private int lineFromLineBuffer(final CharArrayBuffer charbuffer) throws IOException { // discard LF if found int len = this.linebuffer.length(); if (len > 0) { if (this.linebuffer.byteAt(len - 1) == HTTP.LF) { len--; } // discard CR if found if (len > 0) { if (this.linebuffer.byteAt(len - 1) == HTTP.CR) { len--; } } } if (this.ascii) { charbuffer.append(this.linebuffer, 0, len); } else { final ByteBuffer bbuf = ByteBuffer.wrap(this.linebuffer.buffer(), 0, len); len = appendDecoded(charbuffer, bbuf); } this.linebuffer.clear(); return len; } private int lineFromReadBuffer(final CharArrayBuffer charbuffer, final int position) throws IOException { final int off = this.bufferpos; int i = position; this.bufferpos = i + 1; if (i > off && this.buffer[i - 1] == HTTP.CR) { // skip CR if found i--; } int len = i - off; if (this.ascii) { charbuffer.append(this.buffer, off, len); } else { final ByteBuffer bbuf = ByteBuffer.wrap(this.buffer, off, len); len = appendDecoded(charbuffer, bbuf); } return len; } private int appendDecoded( final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { if (!bbuf.hasRemaining()) { return 0; } if (this.decoder == null) { this.decoder = this.charset.newDecoder(); this.decoder.onMalformedInput(this.onMalformedCharAction); this.decoder.onUnmappableCharacter(this.onUnmappableCharAction); } if (this.cbuf == null) { this.cbuf = CharBuffer.allocate(1024); } this.decoder.reset(); int len = 0; while (bbuf.hasRemaining()) { final CoderResult result = this.decoder.decode(bbuf, this.cbuf, true); len += handleDecodingResult(result, charbuffer, bbuf); } final CoderResult result = this.decoder.flush(this.cbuf); len += handleDecodingResult(result, charbuffer, bbuf); this.cbuf.clear(); return len; } private int handleDecodingResult( final CoderResult result, final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { if (result.isError()) { result.throwException(); } this.cbuf.flip(); final int len = this.cbuf.remaining(); while (this.cbuf.hasRemaining()) { charbuffer.append(this.cbuf.get()); } this.cbuf.compact(); return len; } public String readLine() throws IOException { final CharArrayBuffer charbuffer = new CharArrayBuffer(64); final int l = readLine(charbuffer); if (l != -1) { return charbuffer.toString(); } else { return null; } } public HttpTransportMetrics getMetrics() { return this.metrics; } } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/SocketInputBuffer.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/SocketInputBuffe0100644 0000000 0000000 00000006477 12613456016 032373 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 {@code 0} it is set to the value of * {@link Socket#getReceiveBufferSize()}. If resultant number is less * than {@code 1024} it is set to {@code 1024}. * @param params HTTP parameters. */ public SocketInputBuffer( final Socket socket, final int buffersize, final HttpParams params) throws IOException { super(); Args.notNull(socket, "Socket"); this.socket = socket; this.eof = false; int n = buffersize; if (n < 0) { n = socket.getReceiveBufferSize(); } if (n < 1024) { n = 1024; } init(socket.getInputStream(), n, params); } @Override protected int fillBuffer() throws IOException { final int i = super.fillBuffer(); this.eof = i == -1; return i; } public boolean isDataAvailable(final int timeout) throws IOException { boolean result = hasBufferedData(); if (!result) { final int oldtimeout = this.socket.getSoTimeout(); try { this.socket.setSoTimeout(timeout); fillBuffer(); result = hasBufferedData(); } finally { socket.setSoTimeout(oldtimeout); } } return result; } public boolean isEof() { return this.eof; } } ././@LongLink0100644 0000000 0000000 00000000165 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/AbstractSessionOutputBuffer.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/AbstractSessionO0100644 0000000 0000000 00000024632 12613456016 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.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 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpRequestParser.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/HttpRequestParse0100644 0000000 0000000 00000007226 12613456016 032427 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/SocketOutputBuffer.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/io/SocketOutputBuff0100644 0000000 0000000 00000004727 12613456016 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 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 {@code 0} it is set to the value of * {@link Socket#getSendBufferSize()}. If resultant number is less * than {@code 1024} it is set to {@code 1024}. * @param params HTTP parameters. */ public SocketOutputBuffer( final Socket socket, final int buffersize, final HttpParams params) throws IOException { super(); Args.notNull(socket, "Socket"); int n = buffersize; if (n < 0) { n = socket.getSendBufferSize(); } if (n < 1024) { n = 1024; } init(socket.getOutputStream(), n, params); } } httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/0040755 0000000 0000000 00000000000 12613456016 030122 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000160 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/EntityDeserializer.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/EntityDeseri0100644 0000000 0000000 00000012736 12613456016 032463 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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); } } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/EntitySerializer.javahttpcomponents-core-4.4.4/httpcore/src/main/java-deprecated/org/apache/http/impl/entity/EntitySerial0100644 0000000 0000000 00000011157 12613456016 032463 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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(); } } httpcomponents-core-4.4.4/httpcore-nio/0040755 0000000 0000000 00000000000 12613456236 016713 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/pom.xml0100644 0000000 0000000 00000011463 12613456027 020230 0ustar000000000 0000000 4.0.0 org.apache.httpcomponents httpcomponents-core 4.4.4 httpcore-nio Apache HttpCore NIO 2005 Apache HttpComponents Core (non-blocking I/O) http://hc.apache.org/httpcomponents-core-ga jar org.apache.httpcomponents httpcore ${project.version} compile 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://docs.oracle.com/javase/6/docs/api/ http://hc.apache.org/httpcomponents-core-4.4.x/httpcore/apidocs/ 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.4.4/httpcore-nio/src/0040755 0000000 0000000 00000000000 12613456027 017500 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/0040755 0000000 0000000 00000000000 12613456027 021316 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/0040755 0000000 0000000 00000000000 12613456027 022105 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/0040755 0000000 0000000 00000000000 12613456027 023326 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/0040755 0000000 0000000 00000000000 12613456027 024305 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/0040755 0000000 0000000 00000000000 12613456027 026123 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/0040755 0000000 0000000 00000000000 12613456027 026710 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpReverseProxy.javahttpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpReverseProxy.j0100644 0000000 0000000 00000104152 12613456027 032516 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.util.Locale; import java.util.concurrent.atomic.AtomicLong; import org.apache.http.ConnectionReuseStrategy; 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.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.config.ConnectionConfig; import org.apache.http.entity.ContentType; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.EnglishReasonPhraseCatalog; import org.apache.http.impl.nio.DefaultHttpClientIODispatch; import org.apache.http.impl.nio.DefaultHttpServerIODispatch; import org.apache.http.impl.nio.pool.BasicNIOConnPool; import org.apache.http.impl.nio.pool.BasicNIOPoolEntry; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.pool.NIOConnFactory; import org.apache.http.nio.protocol.BasicAsyncResponseProducer; import org.apache.http.nio.protocol.HttpAsyncExchange; import org.apache.http.nio.protocol.HttpAsyncRequestConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestExecutor; import org.apache.http.nio.protocol.HttpAsyncRequestHandler; import org.apache.http.nio.protocol.HttpAsyncRequestHandlerMapper; import org.apache.http.nio.protocol.HttpAsyncRequestProducer; import org.apache.http.nio.protocol.HttpAsyncRequester; import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; import org.apache.http.nio.protocol.HttpAsyncResponseProducer; import org.apache.http.nio.protocol.HttpAsyncService; import org.apache.http.nio.protocol.UriHttpAsyncRequestHandlerMapper; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.pool.PoolStats; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; 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; /** * Asynchronous, fully streaming HTTP/1.1 reverse proxy. */ public class NHttpReverseProxy { public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Usage: NHttpReverseProxy [port]"); System.exit(1); } URI uri = new URI(args[0]); int port = 8080; if (args.length > 1) { port = Integer.parseInt(args[1]); } // Target host HttpHost targetHost = new HttpHost( uri.getHost(), uri.getPort() > 0 ? uri.getPort() : 80, uri.getScheme() != null ? uri.getScheme() : "http"); System.out.println("Reverse proxy to " + targetHost); IOReactorConfig config = IOReactorConfig.custom() .setIoThreadCount(1) .setSoTimeout(3000) .setConnectTimeout(3000) .build(); final ConnectingIOReactor connectingIOReactor = new DefaultConnectingIOReactor(config); final ListeningIOReactor listeningIOReactor = new DefaultListeningIOReactor(config); // Set up HTTP protocol processor for incoming connections HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer("Test/1.1"), new ResponseContent(), new ResponseConnControl() }); // Set up HTTP protocol processor for outgoing connections HttpProcessor outhttpproc = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent("Test/1.1"), new RequestExpectContinue(true) }); ProxyClientProtocolHandler clientHandler = new ProxyClientProtocolHandler(); HttpAsyncRequester executor = new HttpAsyncRequester( outhttpproc, new ProxyOutgoingConnectionReuseStrategy()); ProxyConnPool connPool = new ProxyConnPool(connectingIOReactor, ConnectionConfig.DEFAULT); connPool.setMaxTotal(100); connPool.setDefaultMaxPerRoute(20); UriHttpAsyncRequestHandlerMapper handlerRegistry = new UriHttpAsyncRequestHandlerMapper(); handlerRegistry.register("*", new ProxyRequestHandler(targetHost, executor, connPool)); ProxyServiceHandler serviceHandler = new ProxyServiceHandler( inhttpproc, new ProxyIncomingConnectionReuseStrategy(), handlerRegistry); final IOEventDispatch connectingEventDispatch = new DefaultHttpClientIODispatch( clientHandler, ConnectionConfig.DEFAULT); final IOEventDispatch listeningEventDispatch = new DefaultHttpServerIODispatch( serviceHandler, ConnectionConfig.DEFAULT); Thread t = new Thread(new Runnable() { public void run() { try { connectingIOReactor.execute(connectingEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException ex) { ex.printStackTrace(); } finally { try { listeningIOReactor.shutdown(); } catch (IOException ex2) { ex2.printStackTrace(); } } } }); t.start(); try { listeningIOReactor.listen(new InetSocketAddress(port)); listeningIOReactor.execute(listeningEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException ex) { ex.printStackTrace(); } finally { try { connectingIOReactor.shutdown(); } catch (IOException ex2) { ex2.printStackTrace(); } } } static class ProxyHttpExchange { private final ByteBuffer inBuffer; private final ByteBuffer outBuffer; private volatile String id; private volatile HttpHost target; private volatile HttpAsyncExchange responseTrigger; private volatile IOControl originIOControl; private volatile IOControl clientIOControl; private volatile HttpRequest request; private volatile boolean requestReceived; private volatile HttpResponse response; private volatile boolean responseReceived; private volatile Exception ex; public ProxyHttpExchange() { super(); this.inBuffer = ByteBuffer.allocateDirect(10240); this.outBuffer = ByteBuffer.allocateDirect(10240); } public ByteBuffer getInBuffer() { return this.inBuffer; } public ByteBuffer getOutBuffer() { return this.outBuffer; } public String getId() { return this.id; } public void setId(final String id) { this.id = id; } public HttpHost getTarget() { return this.target; } public void setTarget(final HttpHost target) { this.target = target; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public HttpAsyncExchange getResponseTrigger() { return this.responseTrigger; } public void setResponseTrigger(final HttpAsyncExchange responseTrigger) { this.responseTrigger = responseTrigger; } public IOControl getClientIOControl() { return this.clientIOControl; } public void setClientIOControl(final IOControl clientIOControl) { this.clientIOControl = clientIOControl; } public IOControl getOriginIOControl() { return this.originIOControl; } public void setOriginIOControl(final IOControl originIOControl) { this.originIOControl = originIOControl; } public boolean isRequestReceived() { return this.requestReceived; } public void setRequestReceived() { this.requestReceived = true; } public boolean isResponseReceived() { return this.responseReceived; } public void setResponseReceived() { this.responseReceived = true; } public Exception getException() { return this.ex; } public void setException(final Exception ex) { this.ex = ex; } public void reset() { this.inBuffer.clear(); this.outBuffer.clear(); this.target = null; this.id = null; this.responseTrigger = null; this.clientIOControl = null; this.originIOControl = null; this.request = null; this.requestReceived = false; this.response = null; this.responseReceived = false; this.ex = null; } } static class ProxyRequestHandler implements HttpAsyncRequestHandler { private final HttpHost target; private final HttpAsyncRequester executor; private final BasicNIOConnPool connPool; private final AtomicLong counter; public ProxyRequestHandler( final HttpHost target, final HttpAsyncRequester executor, final BasicNIOConnPool connPool) { super(); this.target = target; this.executor = executor; this.connPool = connPool; this.counter = new AtomicLong(1); } public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) { ProxyHttpExchange httpExchange = (ProxyHttpExchange) context.getAttribute("http-exchange"); if (httpExchange == null) { httpExchange = new ProxyHttpExchange(); context.setAttribute("http-exchange", httpExchange); } synchronized (httpExchange) { httpExchange.reset(); String id = String.format("%08X", this.counter.getAndIncrement()); httpExchange.setId(id); httpExchange.setTarget(this.target); return new ProxyRequestConsumer(httpExchange, this.executor, this.connPool); } } public void handle( final ProxyHttpExchange httpExchange, final HttpAsyncExchange responseTrigger, final HttpContext context) throws HttpException, IOException { synchronized (httpExchange) { Exception ex = httpExchange.getException(); if (ex != null) { System.out.println("[client<-proxy] " + httpExchange.getId() + " " + ex); int status = HttpStatus.SC_INTERNAL_SERVER_ERROR; HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, status, EnglishReasonPhraseCatalog.INSTANCE.getReason(status, Locale.US)); String message = ex.getMessage(); if (message == null) { message = "Unexpected error"; } response.setEntity(new NStringEntity(message, ContentType.DEFAULT_TEXT)); responseTrigger.submitResponse(new BasicAsyncResponseProducer(response)); System.out.println("[client<-proxy] " + httpExchange.getId() + " error response triggered"); } HttpResponse response = httpExchange.getResponse(); if (response != null) { responseTrigger.submitResponse(new ProxyResponseProducer(httpExchange)); System.out.println("[client<-proxy] " + httpExchange.getId() + " response triggered"); } // No response yet. httpExchange.setResponseTrigger(responseTrigger); } } } static class ProxyRequestConsumer implements HttpAsyncRequestConsumer { private final ProxyHttpExchange httpExchange; private final HttpAsyncRequester executor; private final BasicNIOConnPool connPool; private volatile boolean completed; public ProxyRequestConsumer( final ProxyHttpExchange httpExchange, final HttpAsyncRequester executor, final BasicNIOConnPool connPool) { super(); this.httpExchange = httpExchange; this.executor = executor; this.connPool = connPool; } public void close() throws IOException { } public void requestReceived(final HttpRequest request) { synchronized (this.httpExchange) { System.out.println("[client->proxy] " + this.httpExchange.getId() + " " + request.getRequestLine()); this.httpExchange.setRequest(request); this.executor.execute( new ProxyRequestProducer(this.httpExchange), new ProxyResponseConsumer(this.httpExchange), this.connPool); } } public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { synchronized (this.httpExchange) { this.httpExchange.setClientIOControl(ioctrl); // Receive data from the client ByteBuffer buf = this.httpExchange.getInBuffer(); int n = decoder.read(buf); System.out.println("[client->proxy] " + this.httpExchange.getId() + " " + n + " bytes read"); if (decoder.isCompleted()) { System.out.println("[client->proxy] " + this.httpExchange.getId() + " content fully read"); } // If the buffer is full, suspend client input until there is free // space in the buffer if (!buf.hasRemaining()) { ioctrl.suspendInput(); System.out.println("[client->proxy] " + this.httpExchange.getId() + " suspend client input"); } // If there is some content in the input buffer make sure origin // output is active if (buf.position() > 0) { if (this.httpExchange.getOriginIOControl() != null) { this.httpExchange.getOriginIOControl().requestOutput(); System.out.println("[client->proxy] " + this.httpExchange.getId() + " request origin output"); } } } } public void requestCompleted(final HttpContext context) { synchronized (this.httpExchange) { this.completed = true;; System.out.println("[client->proxy] " + this.httpExchange.getId() + " request completed"); this.httpExchange.setRequestReceived(); if (this.httpExchange.getOriginIOControl() != null) { this.httpExchange.getOriginIOControl().requestOutput(); System.out.println("[client->proxy] " + this.httpExchange.getId() + " request origin output"); } } } public Exception getException() { return null; } public ProxyHttpExchange getResult() { return this.httpExchange; } public boolean isDone() { return this.completed; } public void failed(final Exception ex) { System.out.println("[client->proxy] " + ex.toString()); } } static class ProxyRequestProducer implements HttpAsyncRequestProducer { private final ProxyHttpExchange httpExchange; public ProxyRequestProducer(final ProxyHttpExchange httpExchange) { super(); this.httpExchange = httpExchange; } public void close() throws IOException { } public HttpHost getTarget() { synchronized (this.httpExchange) { return this.httpExchange.getTarget(); } } public HttpRequest generateRequest() { synchronized (this.httpExchange) { HttpRequest request = this.httpExchange.getRequest(); System.out.println("[proxy->origin] " + this.httpExchange.getId() + " " + request.getRequestLine()); // Rewrite request!!!! if (request instanceof HttpEntityEnclosingRequest) { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest( request.getRequestLine()); r.setEntity(((HttpEntityEnclosingRequest) request).getEntity()); return r; } else { return new BasicHttpRequest(request.getRequestLine()); } } } public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { synchronized (this.httpExchange) { this.httpExchange.setOriginIOControl(ioctrl); // Send data to the origin server ByteBuffer buf = this.httpExchange.getInBuffer(); buf.flip(); int n = encoder.write(buf); buf.compact(); System.out.println("[proxy->origin] " + this.httpExchange.getId() + " " + n + " bytes written"); // If there is space in the buffer and the message has not been // transferred, make sure the client is sending more data if (buf.hasRemaining() && !this.httpExchange.isRequestReceived()) { if (this.httpExchange.getClientIOControl() != null) { this.httpExchange.getClientIOControl().requestInput(); System.out.println("[proxy->origin] " + this.httpExchange.getId() + " request client input"); } } if (buf.position() == 0) { if (this.httpExchange.isRequestReceived()) { encoder.complete(); System.out.println("[proxy->origin] " + this.httpExchange.getId() + " content fully written"); } else { // Input buffer is empty. Wait until the client fills up // the buffer ioctrl.suspendOutput(); System.out.println("[proxy->origin] " + this.httpExchange.getId() + " suspend origin output"); } } } } public void requestCompleted(final HttpContext context) { synchronized (this.httpExchange) { System.out.println("[proxy->origin] " + this.httpExchange.getId() + " request completed"); } } public boolean isRepeatable() { return false; } public void resetRequest() { } public void failed(final Exception ex) { System.out.println("[proxy->origin] " + ex.toString()); } } static class ProxyResponseConsumer implements HttpAsyncResponseConsumer { private final ProxyHttpExchange httpExchange; private volatile boolean completed; public ProxyResponseConsumer(final ProxyHttpExchange httpExchange) { super(); this.httpExchange = httpExchange; } public void close() throws IOException { } public void responseReceived(final HttpResponse response) { synchronized (this.httpExchange) { System.out.println("[proxy<-origin] " + this.httpExchange.getId() + " " + response.getStatusLine()); this.httpExchange.setResponse(response); HttpAsyncExchange responseTrigger = this.httpExchange.getResponseTrigger(); if (responseTrigger != null && !responseTrigger.isCompleted()) { System.out.println("[client<-proxy] " + this.httpExchange.getId() + " response triggered"); responseTrigger.submitResponse(new ProxyResponseProducer(this.httpExchange)); } } } public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { synchronized (this.httpExchange) { this.httpExchange.setOriginIOControl(ioctrl); // Receive data from the origin ByteBuffer buf = this.httpExchange.getOutBuffer(); int n = decoder.read(buf); System.out.println("[proxy<-origin] " + this.httpExchange.getId() + " " + n + " bytes read"); if (decoder.isCompleted()) { System.out.println("[proxy<-origin] " + this.httpExchange.getId() + " content fully read"); } // If the buffer is full, suspend origin input until there is free // space in the buffer if (!buf.hasRemaining()) { ioctrl.suspendInput(); System.out.println("[proxy<-origin] " + this.httpExchange.getId() + " suspend origin input"); } // If there is some content in the input buffer make sure client // output is active if (buf.position() > 0) { if (this.httpExchange.getClientIOControl() != null) { this.httpExchange.getClientIOControl().requestOutput(); System.out.println("[proxy<-origin] " + this.httpExchange.getId() + " request client output"); } } } } public void responseCompleted(final HttpContext context) { synchronized (this.httpExchange) { if (this.completed) { return; } this.completed = true; System.out.println("[proxy<-origin] " + this.httpExchange.getId() + " response completed"); this.httpExchange.setResponseReceived(); if (this.httpExchange.getClientIOControl() != null) { this.httpExchange.getClientIOControl().requestOutput(); System.out.println("[proxy<-origin] " + this.httpExchange.getId() + " request client output"); } } } public void failed(final Exception ex) { synchronized (this.httpExchange) { if (this.completed) { return; } this.completed = true; this.httpExchange.setException(ex); HttpAsyncExchange responseTrigger = this.httpExchange.getResponseTrigger(); if (responseTrigger != null && !responseTrigger.isCompleted()) { System.out.println("[client<-proxy] " + this.httpExchange.getId() + " " + ex); int status = HttpStatus.SC_INTERNAL_SERVER_ERROR; HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, status, EnglishReasonPhraseCatalog.INSTANCE.getReason(status, Locale.US)); String message = ex.getMessage(); if (message == null) { message = "Unexpected error"; } response.setEntity(new NStringEntity(message, ContentType.DEFAULT_TEXT)); responseTrigger.submitResponse(new BasicAsyncResponseProducer(response)); } } } public boolean cancel() { synchronized (this.httpExchange) { if (this.completed) { return false; } failed(new InterruptedIOException("Cancelled")); return true; } } public ProxyHttpExchange getResult() { return this.httpExchange; } public Exception getException() { return null; } public boolean isDone() { return this.completed; } } static class ProxyResponseProducer implements HttpAsyncResponseProducer { private final ProxyHttpExchange httpExchange; public ProxyResponseProducer(final ProxyHttpExchange httpExchange) { super(); this.httpExchange = httpExchange; } public void close() throws IOException { this.httpExchange.reset(); } public HttpResponse generateResponse() { synchronized (this.httpExchange) { HttpResponse response = this.httpExchange.getResponse(); System.out.println("[client<-proxy] " + this.httpExchange.getId() + " " + response.getStatusLine()); // Rewrite response!!!! BasicHttpResponse r = new BasicHttpResponse(response.getStatusLine()); r.setEntity(response.getEntity()); return r; } } public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { synchronized (this.httpExchange) { this.httpExchange.setClientIOControl(ioctrl); // Send data to the client ByteBuffer buf = this.httpExchange.getOutBuffer(); buf.flip(); int n = encoder.write(buf); buf.compact(); System.out.println("[client<-proxy] " + this.httpExchange.getId() + " " + n + " bytes written"); // If there is space in the buffer and the message has not been // transferred, make sure the origin is sending more data if (buf.hasRemaining() && !this.httpExchange.isResponseReceived()) { if (this.httpExchange.getOriginIOControl() != null) { this.httpExchange.getOriginIOControl().requestInput(); System.out.println("[client<-proxy] " + this.httpExchange.getId() + " request origin input"); } } if (buf.position() == 0) { if (this.httpExchange.isResponseReceived()) { encoder.complete(); System.out.println("[client<-proxy] " + this.httpExchange.getId() + " content fully written"); } else { // Input buffer is empty. Wait until the origin fills up // the buffer ioctrl.suspendOutput(); System.out.println("[client<-proxy] " + this.httpExchange.getId() + " suspend client output"); } } } } public void responseCompleted(final HttpContext context) { synchronized (this.httpExchange) { System.out.println("[client<-proxy] " + this.httpExchange.getId() + " response completed"); } } public void failed(final Exception ex) { System.out.println("[client<-proxy] " + ex.toString()); } } static class ProxyIncomingConnectionReuseStrategy extends DefaultConnectionReuseStrategy { @Override public boolean keepAlive(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpCoreContext.HTTP_CONNECTION); boolean keepAlive = super.keepAlive(response, context); if (keepAlive) { System.out.println("[client->proxy] connection kept alive " + conn); } return keepAlive; } }; static class ProxyOutgoingConnectionReuseStrategy extends DefaultConnectionReuseStrategy { @Override public boolean keepAlive(final HttpResponse response, final HttpContext context) { NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpCoreContext.HTTP_CONNECTION); boolean keepAlive = super.keepAlive(response, context); if (keepAlive) { System.out.println("[proxy->origin] connection kept alive " + conn); } return keepAlive; } }; static class ProxyServiceHandler extends HttpAsyncService { public ProxyServiceHandler( final HttpProcessor httpProcessor, final ConnectionReuseStrategy reuseStrategy, final HttpAsyncRequestHandlerMapper handlerResolver) { super(httpProcessor, reuseStrategy, null, handlerResolver, null); } @Override protected void log(final Exception ex) { ex.printStackTrace(); } @Override public void connected(final NHttpServerConnection conn) { System.out.println("[client->proxy] connection open " + conn); super.connected(conn); } @Override public void closed(final NHttpServerConnection conn) { System.out.println("[client->proxy] connection closed " + conn); super.closed(conn); } } static class ProxyClientProtocolHandler extends HttpAsyncRequestExecutor { public ProxyClientProtocolHandler() { super(); } @Override protected void log(final Exception ex) { ex.printStackTrace(); } @Override public void connected(final NHttpClientConnection conn, final Object attachment) throws IOException, HttpException { System.out.println("[proxy->origin] connection open " + conn); super.connected(conn, attachment); } @Override public void closed(final NHttpClientConnection conn) { System.out.println("[proxy->origin] connection closed " + conn); super.closed(conn); } } static class ProxyConnPool extends BasicNIOConnPool { public ProxyConnPool( final ConnectingIOReactor ioreactor, final ConnectionConfig config) { super(ioreactor, config); } public ProxyConnPool( final ConnectingIOReactor ioreactor, final NIOConnFactory connFactory, final int connectTimeout) { super(ioreactor, connFactory, connectTimeout); } @Override public void release(final BasicNIOPoolEntry entry, boolean reusable) { System.out.println("[proxy->origin] connection released " + entry.getConnection()); super.release(entry, reusable); StringBuilder buf = new StringBuilder(); PoolStats totals = getTotalStats(); buf.append("[total kept alive: ").append(totals.getAvailable()).append("; "); buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable()); buf.append(" of ").append(totals.getMax()).append("]"); System.out.println("[proxy->origin] " + buf.toString()); } } } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/PipeliningHttpClient.javahttpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/PipeliningHttpClien0100644 0000000 0000000 00000015526 12613456027 032552 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.concurrent.FutureCallback; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.nio.DefaultHttpClientIODispatch; import org.apache.http.impl.nio.pool.BasicNIOConnPool; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.protocol.BasicAsyncRequestProducer; import org.apache.http.nio.protocol.BasicAsyncResponseConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestExecutor; import org.apache.http.nio.protocol.HttpAsyncRequester; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; 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; /** * Minimal pipelining HTTP/1.1 client. *

* Please note that this example represents a minimal HTTP client implementation. * It does not support HTTPS as is. * You either need to provide BasicNIOConnPool with a connection factory * that supports SSL or use a more complex HttpAsyncClient. * * @see org.apache.http.impl.nio.pool.BasicNIOConnPool#BasicNIOConnPool(org.apache.http.nio.reactor.ConnectingIOReactor, * org.apache.http.nio.pool.NIOConnFactory, int) * @see org.apache.http.impl.nio.pool.BasicNIOConnFactory */ public class PipeliningHttpClient { public static void main(String[] args) throws Exception { // Create HTTP protocol processing chain HttpProcessor httpproc = HttpProcessorBuilder.create() // Use standard client-side protocol interceptors .add(new RequestContent()) .add(new RequestTargetHost()) .add(new RequestConnControl()) .add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, ConnectionConfig.DEFAULT); // Create client-side I/O reactor final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(2); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester HttpAsyncRequester requester = new HttpAsyncRequester(httpproc); final HttpHost target = new HttpHost("www.apache.org"); List requestProducers = Arrays.asList( new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/index.html")), new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/foundation/index.html")), new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/foundation/how-it-works.html")) ); List responseConsumers = Arrays.asList( new BasicAsyncResponseConsumer(), new BasicAsyncResponseConsumer(), new BasicAsyncResponseConsumer() ); final CountDownLatch latch = new CountDownLatch(1); HttpCoreContext context = HttpCoreContext.create(); requester.executePipelined( target, requestProducers, responseConsumers, pool, context, new FutureCallback>() { @Override public void completed(final List result) { latch.countDown(); for (HttpResponse response: result) { System.out.println(target + "->" + response.getStatusLine()); } } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); latch.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); } } ././@LongLink0100644 0000000 0000000 00000000152 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/ElementalEchoServer.javahttpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/ElementalEchoServer0100644 0000000 0000000 00000007717 12613456027 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.examples.nio; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.nio.reactor.EventMask; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ListeningIOReactor; public class ElementalEchoServer { public static void main(String[] args) throws Exception { IOEventDispatch ioEventDispatch = new DefaultIoEventDispatch(); ListeningIOReactor ioReactor = new DefaultListeningIOReactor(); ioReactor.listen(new InetSocketAddress(8080)); try { ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } static class DefaultIoEventDispatch implements IOEventDispatch { private final ByteBuffer buffer = ByteBuffer.allocate(1024); public void connected(IOSession session) { System.out.println("connected"); session.setEventMask(EventMask.READ); session.setSocketTimeout(20000); } public void inputReady(final IOSession session) { System.out.println("readable"); try { this.buffer.compact(); int bytesRead = session.channel().read(this.buffer); if (this.buffer.position() > 0) { session.setEventMask(EventMask.READ_WRITE); } System.out.println("Bytes read: " + bytesRead); if (bytesRead == -1) { session.close(); } } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } } public void outputReady(final IOSession session) { System.out.println("writeable"); try { this.buffer.flip(); int bytesWritten = session.channel().write(this.buffer); if (!this.buffer.hasRemaining()) { session.setEventMask(EventMask.READ); } System.out.println("Bytes written: " + bytesWritten); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } } public void timeout(final IOSession session) { System.out.println("timeout"); session.close(); } public void disconnected(final IOSession session) { System.out.println("disconnected"); } } } httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpClient.java0100644 0000000 0000000 00000014646 12613456027 031757 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import java.io.InterruptedIOException; import java.util.concurrent.CountDownLatch; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.concurrent.FutureCallback; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.nio.DefaultHttpClientIODispatch; import org.apache.http.impl.nio.pool.BasicNIOConnPool; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.protocol.BasicAsyncRequestProducer; import org.apache.http.nio.protocol.BasicAsyncResponseConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestExecutor; import org.apache.http.nio.protocol.HttpAsyncRequester; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; 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; /** * Minimal asynchronous HTTP/1.1 client. *

* Please note that this example represents a minimal HTTP client implementation. * It does not support HTTPS as is. * You either need to provide BasicNIOConnPool with a connection factory * that supports SSL or use a more complex HttpAsyncClient. * * @see BasicNIOConnPool#BasicNIOConnPool(org.apache.http.nio.reactor.ConnectingIOReactor, * org.apache.http.nio.pool.NIOConnFactory, int) * @see org.apache.http.impl.nio.pool.BasicNIOConnFactory */ public class NHttpClient { public static void main(String[] args) throws Exception { // Create HTTP protocol processing chain HttpProcessor httpproc = HttpProcessorBuilder.create() // Use standard client-side protocol interceptors .add(new RequestContent()) .add(new RequestTargetHost()) .add(new RequestConnControl()) .add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, ConnectionConfig.DEFAULT); // Create client-side I/O reactor final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(2); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester HttpAsyncRequester requester = new HttpAsyncRequester(httpproc); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { new HttpHost("www.apache.org", 80, "http"), new HttpHost("www.verisign.com", 443, "https"), new HttpHost("www.google.com", 80, "http") }; final CountDownLatch latch = new CountDownLatch(targets.length); for (final HttpHost target: targets) { BasicHttpRequest request = new BasicHttpRequest("GET", "/"); HttpCoreContext coreContext = HttpCoreContext.create(); requester.execute( new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, coreContext, // Handle HTTP response from a callback new FutureCallback() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(target + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); } latch.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); } } ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpFileServer.javahttpcomponents-core-4.4.4/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpFileServer.jav0100644 0000000 0000000 00000016252 12613456027 032441 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLDecoder; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import org.apache.http.ExceptionLogger; import org.apache.http.HttpConnection; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.entity.ContentType; import org.apache.http.impl.nio.bootstrap.HttpServer; import org.apache.http.impl.nio.bootstrap.ServerBootstrap; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.entity.NFileEntity; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.BasicAsyncRequestConsumer; import org.apache.http.nio.protocol.BasicAsyncResponseProducer; import org.apache.http.nio.protocol.HttpAsyncExchange; import org.apache.http.nio.protocol.HttpAsyncRequestConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestHandler; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.ssl.SSLContexts; /** * Embedded HTTP/1.1 file server based on a non-blocking I/O model and capable of direct channel * (zero copy) data transfer. */ public class NHttpFileServer { 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 File docRoot = new File(args[0]); int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } SSLContext sslcontext = null; if (port == 8443) { // Initialize SSL context URL url = NHttpFileServer.class.getResource("/my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } sslcontext = SSLContexts.custom() .loadKeyMaterial(url, "secret".toCharArray(), "secret".toCharArray()) .build(); } IOReactorConfig config = IOReactorConfig.custom() .setSoTimeout(15000) .setTcpNoDelay(true) .build(); final HttpServer server = ServerBootstrap.bootstrap() .setListenerPort(port) .setServerInfo("Test/1.1") .setIOReactorConfig(config) .setSslContext(sslcontext) .setExceptionLogger(ExceptionLogger.STD_ERR) .registerHandler("*", new HttpFileHandler(docRoot)) .create(); server.start(); server.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(5, TimeUnit.SECONDS); } }); } static class HttpFileHandler implements HttpAsyncRequestHandler { private final File docRoot; public HttpFileHandler(final File docRoot) { super(); this.docRoot = docRoot; } 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(); handleInternal(request, response, context); httpexchange.submitResponse(new BasicAsyncResponseProducer(response)); } private void handleInternal( 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(); final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8")); if (!file.exists()) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); NStringEntity entity = new NStringEntity( "

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); NStringEntity entity = new NStringEntity( "

Access denied

", ContentType.create("text/html", "UTF-8")); response.setEntity(entity); System.out.println("Cannot read file " + file.getPath()); } else { HttpCoreContext coreContext = HttpCoreContext.adapt(context); HttpConnection conn = coreContext.getConnection(HttpConnection.class); response.setStatusCode(HttpStatus.SC_OK); NFileEntity body = new NFileEntity(file, ContentType.create("text/html")); response.setEntity(body); System.out.println(conn + ": serving file " + file.getPath()); } } } } httpcomponents-core-4.4.4/httpcore-nio/src/test/0040755 0000000 0000000 00000000000 12613456024 020454 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/0040755 0000000 0000000 00000000000 12613456023 021374 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/0040755 0000000 0000000 00000000000 12613456023 022163 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/0040755 0000000 0000000 00000000000 12613456023 023404 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/0040755 0000000 0000000 00000000000 12613456024 024364 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/ReadableByteChannelMock.java0100644 0000000 0000000 00000005523 12613456024 031657 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; public class ReadableByteChannelMock implements ReadableByteChannel { private final String[] chunks; private final Charset charset; private int chunkCount = 0; private ByteBuffer currentChunk; private boolean eof = false; private boolean closed = false; public ReadableByteChannelMock(final String[] chunks, final Charset charset) { super(); this.chunks = chunks; this.charset = charset; } private void prepareChunk() { if (this.currentChunk == null || !this.currentChunk.hasRemaining()) { if (this.chunkCount < this.chunks.length) { final String s = this.chunks[this.chunkCount]; this.chunkCount++; this.currentChunk = ByteBuffer.wrap(s.getBytes(this.charset)); } else { this.eof = true; } } } @Override public int read(final ByteBuffer dst) throws IOException { if (this.closed) { throw new ClosedChannelException(); } prepareChunk(); if (this.eof) { return -1; } int i = 0; while (dst.hasRemaining() && this.currentChunk.hasRemaining()) { dst.put(this.currentChunk.get()); i++; } return i; } @Override public void close() throws IOException { this.closed = true; } @Override public boolean isOpen() { return !this.closed && !this.eof; } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/WritableByteChannelMock.java0100644 0000000 0000000 00000011551 12613456023 031726 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import org.apache.http.nio.util.ExpandableBuffer; import org.apache.http.nio.util.HeapByteBufferAllocator; public class WritableByteChannelMock implements WritableByteChannel { static class InternalBuffer extends ExpandableBuffer { private final int capacityLimit; private int curCapacity; public InternalBuffer(final int buffersize, final int capacityLimit) { super(buffersize, HeapByteBufferAllocator.INSTANCE); this.capacityLimit = capacityLimit; this.curCapacity = capacityLimit; } public int write(final ByteBuffer src) { if (src == null) { return 0; } setInputMode(); if (this.capacityLimit > 0) { if (this.curCapacity > 0) { final int requiredCapacity = this.buffer.position() + this.curCapacity; ensureCapacity(requiredCapacity); int count = 0; while (src.hasRemaining() && this.curCapacity > 0) { this.buffer.put(src.get()); count++; this.curCapacity--; } return count; } else { return 0; } } else { final int chunk = src.remaining(); final int requiredCapacity = this.buffer.position() + src.remaining(); ensureCapacity(requiredCapacity); this.buffer.put(src); return chunk; } } @Override protected void clear() { super.clear(); } public void resetCapacity() { this.curCapacity = this.capacityLimit; } private static String toString( final byte[] b, final int off, final int len, final Charset charset) { return new String(b, off, len, charset); } public String dump(final Charset charset) { setOutputMode(); if (this.buffer.hasArray()) { return toString(this.buffer.array(), this.buffer.position(), this.buffer.limit(), charset); } else { final ByteBuffer dup = this.buffer.duplicate(); final byte[] b = new byte[dup.remaining()]; int i = 0; while (dup.hasRemaining()) { b[i] = dup.get(); i++; } return toString(b, 0, b.length, charset); } } } private final InternalBuffer buf; private boolean closed; public WritableByteChannelMock(final int size, final int capacityLimit) { super(); this.buf = new InternalBuffer(size, capacityLimit); } public WritableByteChannelMock(final int size) { this(size, 0); } @Override public int write(final ByteBuffer src) throws IOException { if (this.closed) { throw new ClosedChannelException(); } return this.buf.write(src); } @Override public boolean isOpen() { return !this.closed; } @Override public void close() throws IOException { this.closed = true; } public void flush() { this.buf.resetCapacity(); } public void reset() { this.buf.resetCapacity(); this.buf.clear(); } public String dump(final Charset charset){ return this.buf.dump(charset); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/ByteChannelMock.java0100644 0000000 0000000 00000004445 12613456024 030241 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.ByteBuffer; import java.nio.channels.ByteChannel; public class ByteChannelMock implements ByteChannel { private final ReadableByteChannelMock readableChannel; private final WritableByteChannelMock writableChannel; private boolean closed; public ByteChannelMock( final ReadableByteChannelMock readableChannel, final WritableByteChannelMock writableChannel) { super(); this.readableChannel = readableChannel; this.writableChannel = writableChannel; } @Override public int read(final ByteBuffer dst) throws IOException { return this.readableChannel.read(dst); } @Override public int write(final ByteBuffer src) throws IOException { return this.writableChannel.write(src); } @Override public boolean isOpen() { return !this.closed; } @Override public void close() throws IOException { if (this.closed) { return; } this.closed = true; this.readableChannel.close(); this.writableChannel.close(); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/OoopsieRuntimeException.java0100644 0000000 0000000 00000002620 12613456023 032063 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http; public class OoopsieRuntimeException extends RuntimeException { private static final long serialVersionUID = 662807254163212266L; public OoopsieRuntimeException() { super("Ooopsie!!!"); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/0040755 0000000 0000000 00000000000 12613456024 025151 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/0040755 0000000 0000000 00000000000 12613456023 027011 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000164 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestHttpAsyncRequestExecutor.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestHttpAsyncReque0100644 0000000 0000000 00000104070 12613456023 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.nio.protocol; import java.io.IOException; import java.net.SocketTimeoutException; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.HttpAsyncRequestExecutor.State; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class TestHttpAsyncRequestExecutor { private HttpAsyncRequestExecutor protocolHandler; private HttpContext connContext; private NHttpClientConnection conn; private HttpAsyncClientExchangeHandler exchangeHandler; private ContentEncoder encoder; private ContentDecoder decoder; @Before public void setUp() throws Exception { this.protocolHandler = new HttpAsyncRequestExecutor(); this.connContext = new BasicHttpContext(); this.conn = Mockito.mock(NHttpClientConnection.class); this.exchangeHandler = Mockito.mock(HttpAsyncClientExchangeHandler.class); this.encoder = Mockito.mock(ContentEncoder.class); this.decoder = Mockito.mock(ContentDecoder.class); Mockito.when(this.conn.getContext()).thenReturn(this.connContext); } @After public void tearDown() throws Exception { } @Test public void testConnected() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); Mockito.when(this.exchangeHandler.generateRequest()).thenReturn(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); this.protocolHandler.connected(this.conn, null); final State state = (State) this.connContext.getAttribute( HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE); Assert.assertNotNull(state); Mockito.verify(this.exchangeHandler).generateRequest(); Assert.assertSame(request, state.getRequest()); Mockito.verify(this.conn).submitRequest(request); Mockito.verify(this.exchangeHandler).requestCompleted(); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); Assert.assertEquals("request state: COMPLETED; request: GET / HTTP/1.1; " + "response state: READY; response: ; valid: true;", state.toString()); } @Test public void testClosed() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.READY); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); this.protocolHandler.closed(this.conn); Mockito.verify(this.exchangeHandler, Mockito.never()).close(); } @Test public void testClosedNullState() throws Exception { this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); this.protocolHandler.closed(this.conn); Mockito.verify(this.exchangeHandler).close(); } @Test public void testClosedInconsistentState() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.INIT); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); this.protocolHandler.closed(this.conn); Mockito.verify(this.exchangeHandler).failed(Mockito.any(ConnectionClosedException.class)); } @Test public void testHttpExceptionHandling() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.COMPLETED); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final HttpException httpex = new HttpException(); this.protocolHandler.exception(this.conn, httpex); Mockito.verify(this.exchangeHandler).failed(httpex); Mockito.verify(this.conn).shutdown(); } @Test public void testIOExceptionHandling() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.COMPLETED); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final IOException ioex = new IOException(); this.protocolHandler.exception(this.conn, ioex); Mockito.verify(this.exchangeHandler).failed(ioex); Mockito.verify(this.conn).shutdown(); } @Test public void testBasicRequest() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final HttpRequest request = new BasicHttpRequest("GET", "/"); Mockito.when(this.exchangeHandler.generateRequest()).thenReturn(request); this.protocolHandler.requestReady(this.conn); Mockito.verify(this.exchangeHandler).generateRequest(); Assert.assertSame(request, state.getRequest()); Mockito.verify(this.conn).submitRequest(request); Mockito.verify(this.exchangeHandler).requestCompleted(); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); } @Test public void testNullRequest() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.exchangeHandler.generateRequest()).thenReturn(null); this.protocolHandler.requestReady(this.conn); Mockito.verify(this.exchangeHandler).generateRequest(); Assert.assertNull(state.getRequest()); Mockito.verify(this.conn, Mockito.times(1)).suspendOutput(); Mockito.verify(this.conn, Mockito.never()).submitRequest(Mockito.any()); } @Test public void testEntityEnclosingRequestWithoutExpectContinue() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setEntity(new NStringEntity("stuff")); Mockito.when(this.exchangeHandler.generateRequest()).thenReturn(request); this.protocolHandler.requestReady(this.conn); Mockito.verify(this.exchangeHandler).generateRequest(); Assert.assertSame(request, state.getRequest()); Mockito.verify(this.conn).submitRequest(request); Mockito.verify(this.exchangeHandler, Mockito.never()).requestCompleted(); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); } @Test public void testEntityEnclosingRequestWithExpectContinue() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); Mockito.when(this.exchangeHandler.generateRequest()).thenReturn(request); Mockito.when(this.conn.getSocketTimeout()).thenReturn(1000); this.protocolHandler.requestReady(this.conn); Mockito.verify(this.exchangeHandler).generateRequest(); Assert.assertSame(request, state.getRequest()); Mockito.verify(this.conn).submitRequest(request); Mockito.verify(this.conn).setSocketTimeout(3000); Assert.assertEquals(1000, state.getTimeout()); Mockito.verify(this.exchangeHandler, Mockito.never()).requestCompleted(); Assert.assertEquals(MessageState.ACK_EXPECTED, state.getRequestState()); } @Test public void testRequestContentOutput() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.BODY_STREAM); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.encoder.isCompleted()).thenReturn(Boolean.FALSE); this.protocolHandler.outputReady(this.conn, this.encoder); Mockito.verify(this.exchangeHandler).produceContent(this.encoder, this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); } @Test public void testRequestContentOutputCompleted() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.BODY_STREAM); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.encoder.isCompleted()).thenReturn(Boolean.TRUE); this.protocolHandler.outputReady(this.conn, this.encoder); Mockito.verify(this.exchangeHandler).produceContent(this.encoder, this.conn); Mockito.verify(this.exchangeHandler).requestCompleted(); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); } @Test public void testRequestContentContinueExpected() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.ACK_EXPECTED); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); this.protocolHandler.outputReady(this.conn, this.encoder); Mockito.verify(this.conn).suspendOutput(); Mockito.verify(this.exchangeHandler, Mockito.never()).produceContent(this.encoder, this.conn); Assert.assertEquals(MessageState.ACK_EXPECTED, state.getRequestState()); } @Test public void testBasicResponse() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); final HttpRequest request = new BasicHttpRequest("GET", "/"); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); Assert.assertSame(response, state.getResponse()); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); } @Test public void testResponseContinue() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.ACK_EXPECTED); state.setTimeout(1000); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setEntity(new NStringEntity("stuff")); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Continue"); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); Assert.assertNull(state.getResponse()); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.conn).setSocketTimeout(1000); Mockito.verify(this.conn).requestOutput(); } @Test public void testResponseContinueOutOfSequence() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.COMPLETED); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setEntity(new NStringEntity("stuff")); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Continue"); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); Assert.assertNull(state.getResponse()); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); Mockito.verify(this.conn, Mockito.never()).requestOutput(); } @Test(expected=HttpException.class) public void testResponseUnsupported1xx() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.ACK_EXPECTED); state.setTimeout(1000); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setEntity(new NStringEntity("stuff")); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 111, "WTF?"); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); } @Test public void testResponseExpectationFailed() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.ACK_EXPECTED); state.setTimeout(1000); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setEntity(new NStringEntity("stuff")); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 403, "Unauthorized"); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); Assert.assertSame(response, state.getResponse()); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); Mockito.verify(this.conn).setSocketTimeout(1000); Mockito.verify(this.conn).resetOutput(); } @Test public void testEarlyResponse() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.BODY_STREAM); state.setTimeout(1000); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setEntity(new NStringEntity("stuff")); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 403, "Unauthorized"); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); Assert.assertSame(response, state.getResponse()); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); Mockito.verify(this.conn).suspendOutput(); Mockito.verify(this.conn).resetOutput(); Assert.assertFalse(state.isValid()); } @Test public void testResponseToHead() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); final HttpRequest request = new BasicHttpRequest("HEAD", "/"); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); Assert.assertEquals(MessageState.READY, state.getResponseState()); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertNull(state.getRequest()); Assert.assertNull(state.getResponse()); Mockito.verify(this.exchangeHandler).responseReceived(response); Mockito.verify(this.conn).resetInput(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testResponseToConnect() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); final HttpRequest request = new BasicHttpRequest("Connect", "/"); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); Assert.assertEquals(MessageState.READY, state.getResponseState()); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertNull(state.getRequest()); Assert.assertNull(state.getResponse()); Mockito.verify(this.exchangeHandler).responseReceived(response); Mockito.verify(this.conn).resetInput(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testResponseNotModified() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); final HttpRequest request = new BasicHttpRequest("Connect", "/"); state.setRequest(request); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not modified"); response.setEntity(new BasicHttpEntity()); Mockito.when(this.conn.getHttpResponse()).thenReturn(response); this.protocolHandler.responseReceived(this.conn); Assert.assertEquals(MessageState.READY, state.getResponseState()); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertNull(state.getRequest()); Assert.assertNull(state.getResponse()); Assert.assertNull(response.getEntity()); Mockito.verify(this.exchangeHandler).responseReceived(response); Mockito.verify(this.conn).resetInput(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testResponseContentInput() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setResponseState(MessageState.BODY_STREAM); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.decoder.isCompleted()).thenReturn(Boolean.FALSE); this.protocolHandler.inputReady(this.conn, this.decoder); Mockito.verify(this.exchangeHandler).consumeContent(this.decoder, this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); } @Test public void testResponseContentOutputCompleted() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); final HttpRequest request = new BasicHttpRequest("GET", "/"); state.setRequest(request); state.setResponseState(MessageState.BODY_STREAM); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); state.setResponse(response); Mockito.when(this.exchangeHandler.isDone()).thenReturn(Boolean.TRUE); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.decoder.isCompleted()).thenReturn(Boolean.TRUE); this.protocolHandler.inputReady(this.conn, this.decoder); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.exchangeHandler).consumeContent(this.decoder, this.conn); Mockito.verify(this.exchangeHandler).responseCompleted(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testResponseContentOutputCompletedHandlerNotDone() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setResponseState(MessageState.BODY_STREAM); final HttpRequest request = new BasicHttpRequest("GET", "/"); state.setRequest(request); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); state.setResponse(response); Mockito.when(this.exchangeHandler.isDone()).thenReturn(Boolean.FALSE); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.decoder.isCompleted()).thenReturn(Boolean.TRUE); Mockito.when(this.conn.isOpen()).thenReturn(Boolean.TRUE); this.protocolHandler.inputReady(this.conn, this.decoder); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.exchangeHandler).consumeContent(this.decoder, this.conn); Mockito.verify(this.exchangeHandler).responseCompleted(); Mockito.verify(this.conn).requestOutput(); } @Test public void testResponseContentOutputCompletedHandlerNotDoneConnClosed() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); final HttpRequest request = new BasicHttpRequest("GET", "/"); state.setRequest(request); state.setResponseState(MessageState.BODY_STREAM); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); state.setResponse(response); Mockito.when(this.exchangeHandler.isDone()).thenReturn(Boolean.FALSE); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.decoder.isCompleted()).thenReturn(Boolean.TRUE); Mockito.when(this.conn.isOpen()).thenReturn(Boolean.FALSE); this.protocolHandler.inputReady(this.conn, this.decoder); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.exchangeHandler).consumeContent(this.decoder, this.conn); Mockito.verify(this.exchangeHandler).responseCompleted(); Mockito.verify(this.conn, Mockito.never()).requestOutput(); } @Test public void testResponseInvalidState() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); final HttpRequest request = new BasicHttpRequest("GET", "/"); state.setRequest(request); state.setResponseState(MessageState.BODY_STREAM); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); state.setResponse(response); state.invalidate(); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.decoder.isCompleted()).thenReturn(Boolean.TRUE); this.protocolHandler.inputReady(this.conn, this.decoder); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.exchangeHandler).consumeContent(this.decoder, this.conn); Mockito.verify(this.conn).close(); } @Test public void testEndOfInput() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.protocolHandler.endOfInput(this.conn); Mockito.verify(this.conn).close(); } @Test public void testPrematureEndOfInput() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.COMPLETED); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); this.protocolHandler.endOfInput(this.conn); Assert.assertFalse(state.isValid()); Mockito.verify(this.conn).close(); Mockito.verify(this.exchangeHandler).failed(Mockito.any(ConnectionClosedException.class)); } @Test public void testPrematureEndOfInputRequestReady() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.READY); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); this.protocolHandler.endOfInput(this.conn); Assert.assertTrue(state.isValid()); Mockito.verify(this.exchangeHandler).inputTerminated(); } @Test public void testTimeoutNoHandler() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); Mockito.when(this.conn.getStatus()).thenReturn( NHttpConnection.ACTIVE, NHttpConnection.CLOSING); this.protocolHandler.timeout(this.conn); Mockito.verify(this.conn).close(); Mockito.verify(this.conn).setSocketTimeout(250); } @Test public void testExpectContinueTimeout() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.ACK_EXPECTED); state.setTimeout(1000); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); this.protocolHandler.timeout(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertTrue(state.isValid()); Mockito.verify(this.conn).setSocketTimeout(1000); Mockito.verify(this.conn).requestOutput(); } @Test public void testTimeoutActiveConnection() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.BODY_STREAM); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.conn.getStatus()).thenReturn(NHttpConnection.ACTIVE, NHttpConnection.CLOSED); this.protocolHandler.timeout(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertFalse(state.isValid()); Mockito.verify(this.exchangeHandler).failed(Mockito.any(SocketTimeoutException.class)); Mockito.verify(this.exchangeHandler).close(); Mockito.verify(this.conn).close(); Mockito.verify(this.conn, Mockito.never()).setSocketTimeout(Mockito.anyInt()); } @Test public void testTimeoutActiveConnectionBufferedData() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.BODY_STREAM); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.conn.getStatus()).thenReturn(NHttpConnection.ACTIVE, NHttpConnection.CLOSING); this.protocolHandler.timeout(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertFalse(state.isValid()); Mockito.verify(this.exchangeHandler).failed(Mockito.any(SocketTimeoutException.class)); Mockito.verify(this.exchangeHandler).close(); Mockito.verify(this.conn).close(); Mockito.verify(this.conn).setSocketTimeout(250); } @Test public void testTimeoutClosingConnection() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); state.setRequestState(MessageState.BODY_STREAM); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.conn.getStatus()).thenReturn(NHttpConnection.CLOSING, NHttpConnection.CLOSED); this.protocolHandler.timeout(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertFalse(state.isValid()); Mockito.verify(this.exchangeHandler).failed(Mockito.any(SocketTimeoutException.class)); Mockito.verify(this.exchangeHandler).close(); Mockito.verify(this.conn).shutdown(); } @Test public void testExchangeDone() throws Exception { final State state = new HttpAsyncRequestExecutor.State(); final HttpRequest request = new BasicHttpRequest("GET", "/"); state.setRequest(request); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); state.setResponse(response); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_EXCHANGE_STATE, state); this.connContext.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, this.exchangeHandler); Mockito.when(this.exchangeHandler.isDone()).thenReturn(Boolean.TRUE); Assert.assertEquals("request state: READY; request: GET / HTTP/1.1; " + "response state: READY; response: HTTP/1.1 200 OK; valid: true;", state.toString()); this.protocolHandler.requestReady(this.conn); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); } } ././@LongLink0100644 0000000 0000000 00000000166 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncResponseConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncResp0100644 0000000 0000000 00000011156 12613456023 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.nio.protocol; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.http.HttpResponse; import org.apache.http.entity.StringEntity; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class TestBasicAsyncResponseConsumer { private BasicAsyncResponseConsumer consumer; @Mock private HttpResponse response; @Mock private HttpContext context; @Mock private ContentDecoder decoder; @Mock private IOControl ioctrl; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); consumer = Mockito.spy(new BasicAsyncResponseConsumer()); } @After public void tearDown() throws Exception { } @Test public void testResponseProcessing() throws Exception { when(response.getEntity()).thenReturn(new StringEntity("stuff")); consumer.responseReceived(response); consumer.consumeContent(decoder, ioctrl); consumer.responseCompleted(context); verify(consumer).releaseResources(); verify(consumer).buildResult(context); Assert.assertTrue(consumer.isDone()); Assert.assertSame(response, consumer.getResult()); consumer.responseCompleted(context); verify(consumer, times(1)).releaseResources(); verify(consumer, times(1)).buildResult(context); } @Test public void testResponseProcessingWithException() throws Exception { when(response.getEntity()).thenReturn(new StringEntity("stuff")); final RuntimeException ooopsie = new RuntimeException(); when(consumer.buildResult(context)).thenThrow(ooopsie); consumer.responseReceived(response); consumer.consumeContent(decoder, ioctrl); consumer.responseCompleted(context); verify(consumer).releaseResources(); Assert.assertTrue(consumer.isDone()); Assert.assertSame(ooopsie, consumer.getException()); } @Test public void testCancel() throws Exception { Assert.assertTrue(consumer.cancel()); verify(consumer).releaseResources(); Assert.assertTrue(consumer.isDone()); Assert.assertFalse(consumer.cancel()); verify(consumer, times(1)).releaseResources(); } @Test public void testFailed() throws Exception { final RuntimeException ooopsie = new RuntimeException(); consumer.failed(ooopsie); verify(consumer).releaseResources(); Assert.assertTrue(consumer.isDone()); Assert.assertSame(ooopsie, consumer.getException()); } @Test public void testFailedAfterDone() throws Exception { final RuntimeException ooopsie = new RuntimeException(); consumer.cancel(); consumer.failed(ooopsie); verify(consumer, times(1)).releaseResources(); Assert.assertTrue(consumer.isDone()); Assert.assertNull(consumer.getException()); } @Test public void testClose() throws Exception { consumer.close(); verify(consumer).releaseResources(); Assert.assertTrue(consumer.isDone()); consumer.close(); verify(consumer, times(1)).releaseResources(); } } ././@LongLink0100644 0000000 0000000 00000000165 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncRequestProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncRequ0100644 0000000 0000000 00000010513 12613456023 032445 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.entity.HttpAsyncContentProducer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class TestBasicAsyncRequestProducer { private BasicAsyncRequestProducer producer; private HttpHost target; @Mock private HttpAsyncContentProducer contentProducer; @Mock private HttpEntityEnclosingRequest request; @Mock private ContentEncoder encoder; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); target = new HttpHost("localhost"); producer = new BasicAsyncRequestProducer(target, request, contentProducer); } @After public void tearDown() throws Exception { } @Test(expected=IllegalArgumentException.class) public void testNullTarget3ArgConstructor() throws Exception { producer = new BasicAsyncRequestProducer(null, request, contentProducer); } @Test(expected=IllegalArgumentException.class) public void testNullRequest3ArgConstructor() throws Exception { producer = new BasicAsyncRequestProducer(target, null, contentProducer); } @Test(expected=IllegalArgumentException.class) public void testNullTarget2ArgConstructor() throws Exception { producer = new BasicAsyncRequestProducer(null, request); } @Test(expected=IllegalArgumentException.class) public void testNullRequest2ArgConstructor() throws Exception { producer = new BasicAsyncRequestProducer(target, null); } @Test public void testGenerateRequest() { final HttpRequest res = producer.generateRequest(); Assert.assertSame(request, res); } @Test public void testGetTarget() { final HttpHost res = producer.getTarget(); Assert.assertSame(target, res); } @SuppressWarnings("boxing") @Test public void testProduceContentEncoderCompleted() throws Exception { when(encoder.isCompleted()).thenReturn(Boolean.TRUE); producer.produceContent(encoder, null); verify(contentProducer, times(1)).close(); } @SuppressWarnings("boxing") @Test public void testProduceContentEncoderNotCompleted() throws Exception { when(encoder.isCompleted()).thenReturn(Boolean.FALSE); producer.produceContent(encoder, null); verify(contentProducer, times(0)).close(); } @Test public void testResetRequest() throws Exception { producer.resetRequest(); verify(contentProducer, times(1)).close(); } @Test public void testClose() throws Exception { producer.close(); verify(contentProducer, times(1)).close(); } @Test public void testToString() { Assert.assertEquals(target + " " + request + " " + contentProducer, producer.toString()); } } ././@LongLink0100644 0000000 0000000 00000000164 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncRequestHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncRequ0100644 0000000 0000000 00000007152 12613456023 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.nio.protocol; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.message.BasicRequestLine; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class TestBasicAsyncRequestHandler { private HttpRequestHandler requestHandler; private BasicAsyncRequestHandler asyncRequestHandler; private HttpContext context; private HttpRequest request; private HttpResponse response; private HttpAsyncExchange httpexchange; @Before public void setUp() throws Exception { this.requestHandler = Mockito.mock(HttpRequestHandler.class); this.asyncRequestHandler = new BasicAsyncRequestHandler(this.requestHandler); this.context = new BasicHttpContext(); this.request = Mockito.mock(HttpRequest.class); this.response = Mockito.mock(HttpResponse.class); this.httpexchange = Mockito.mock(HttpAsyncExchange.class); Mockito.when(this.httpexchange.getRequest()).thenReturn(this.request); Mockito.when(this.httpexchange.getResponse()).thenReturn(this.response); } @After public void tearDown() throws Exception { } @Test public void testInvalidConstruction() throws Exception { try { new BasicAsyncRequestHandler(null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } } @Test public void testProcessRequest() throws Exception { final HttpAsyncRequestConsumer requestConsumer = this.asyncRequestHandler.processRequest( this.request, this.context); Assert.assertTrue(requestConsumer instanceof BasicAsyncRequestConsumer); } @Test public void testHandleRequest() throws Exception { Mockito.when(this.request.getRequestLine()).thenReturn(new BasicRequestLine("GET", "/", HttpVersion.HTTP_1_0)); this.asyncRequestHandler.handle(this.request, this.httpexchange, this.context); Mockito.verify(this.requestHandler).handle( Mockito.eq(this.request), Mockito.eq(this.response), Mockito.eq(this.context)); Mockito.verify(this.httpexchange).submitResponse(); } } ././@LongLink0100644 0000000 0000000 00000000154 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestHttpAsyncService.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestHttpAsyncServi0100644 0000000 0000000 00000202066 12613456023 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.nio.protocol; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Queue; 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.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.concurrent.Cancellable; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.HttpAsyncService.Incoming; import org.apache.http.nio.protocol.HttpAsyncService.Outgoing; import org.apache.http.nio.protocol.HttpAsyncService.PipelineEntry; import org.apache.http.nio.protocol.HttpAsyncService.State; import org.apache.http.nio.reactor.SessionBufferStatus; 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.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatcher; import org.mockito.Mockito; public class TestHttpAsyncService { private UriHttpAsyncRequestHandlerMapper handlerResolver; private HttpAsyncService protocolHandler; private HttpProcessor httpProcessor; private ConnectionReuseStrategy reuseStrategy; private HttpResponseFactory responseFactory; private HttpContext connContext; private NHttpServerConnection conn; private HttpAsyncRequestHandler requestHandler; private HttpAsyncRequestConsumer requestConsumer; private HttpAsyncResponseProducer responseProducer; private ContentEncoder encoder; private ContentDecoder decoder; private Cancellable cancellable; @SuppressWarnings("unchecked") @Before public void setUp() throws Exception { this.requestHandler = Mockito.mock(HttpAsyncRequestHandler.class); this.requestConsumer = Mockito.mock(HttpAsyncRequestConsumer.class); this.responseProducer = Mockito.mock(HttpAsyncResponseProducer.class); this.handlerResolver = new UriHttpAsyncRequestHandlerMapper(); this.handlerResolver.register("/", this.requestHandler); this.httpProcessor = Mockito.mock(HttpProcessor.class); this.reuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); this.responseFactory = DefaultHttpResponseFactory.INSTANCE; this.protocolHandler = new HttpAsyncService( this.httpProcessor, this.reuseStrategy, this.responseFactory, this.handlerResolver, null); this.connContext = new BasicHttpContext(); this.conn = Mockito.mock(NHttpServerConnection.class); this.encoder = Mockito.mock(ContentEncoder.class); this.decoder = Mockito.mock(ContentDecoder.class); this.cancellable = Mockito.mock(Cancellable.class); Mockito.when(this.conn.getContext()).thenReturn(this.connContext); } @After public void tearDown() throws Exception { } @Test(expected=IllegalArgumentException.class) public void testInvalidConstruction() throws Exception { new HttpAsyncService(null, this.reuseStrategy, this.responseFactory, this.handlerResolver, null); } @Test public void testConnected() throws Exception { this.protocolHandler.connected(this.conn); final State state = (State) this.connContext.getAttribute( HttpAsyncService.HTTP_EXCHANGE_STATE); Assert.assertNotNull(state); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Assert.assertEquals("[incoming READY; outgoing READY]", state.toString()); } @Test public void testClosed() throws Exception { final State state = new State(); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.COMPLETED); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); state.setCancellable(this.cancellable); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); this.protocolHandler.closed(this.conn); Mockito.verify(this.requestConsumer).close(); Mockito.verify(this.responseProducer).close(); Mockito.verify(this.cancellable).cancel(); } @Test public void testHttpExceptionHandling() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.READY); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setCancellable(this.cancellable); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpException httpex = new HttpException(); this.protocolHandler.exception(this.conn, httpex); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); final Outgoing outgoing = state.getOutgoing(); Assert.assertNotNull(outgoing); Assert.assertNotNull(outgoing.getProducer()); Assert.assertNotNull(outgoing.getResponse()); Assert.assertEquals(500, outgoing.getResponse().getStatusLine().getStatusCode()); Mockito.verify(this.requestConsumer).failed(httpex); Mockito.verify(this.requestConsumer).close(); Mockito.verify(this.cancellable).cancel(); Mockito.verify(this.conn, Mockito.never()).shutdown(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testExceptionHandlingNoState() throws Exception { this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, null); final Exception ex = new Exception("Oopsie"); this.protocolHandler.exception(conn, ex); Mockito.verify(conn).getContext(); Mockito.verify(conn).shutdown(); Mockito.verifyNoMoreInteractions(conn); } @Test public void testExceptionHandlingRuntimeException() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.READY); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); state.setCancellable(this.cancellable); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.doThrow(new RuntimeException()).when(this.httpProcessor).process( Mockito.any(HttpResponse.class), Mockito.any(HttpContext.class)); final HttpException httpex = new HttpException(); try { this.protocolHandler.exception(this.conn, httpex); Assert.fail("RuntimeException expected"); } catch (final RuntimeException ex) { Mockito.verify(this.conn).shutdown(); Mockito.verify(this.requestConsumer).failed(httpex); Mockito.verify(this.requestConsumer, Mockito.atLeastOnce()).close(); Mockito.verify(this.responseProducer).failed(httpex); Mockito.verify(this.responseProducer, Mockito.atLeastOnce()).close(); Mockito.verify(this.cancellable).cancel(); } } @Test public void testHttpExceptionHandlingIOException() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.READY); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); state.setCancellable(this.cancellable); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.doThrow(new IOException()).when(this.httpProcessor).process( Mockito.any(HttpResponse.class), Mockito.any(HttpContext.class)); final HttpException httpex = new HttpException(); this.protocolHandler.exception(this.conn, httpex); Mockito.verify(this.conn).shutdown(); Mockito.verify(this.requestConsumer).failed(httpex); Mockito.verify(this.requestConsumer, Mockito.atLeastOnce()).close(); Mockito.verify(this.responseProducer).failed(httpex); Mockito.verify(this.responseProducer, Mockito.atLeastOnce()).close(); Mockito.verify(this.cancellable).cancel(); } @Test public void testHttpExceptionHandlingResponseSubmitted() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.READY); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.conn.isResponseSubmitted()).thenReturn(Boolean.TRUE); final HttpException httpex = new HttpException(); this.protocolHandler.exception(this.conn, httpex); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.conn).shutdown(); Mockito.verify(this.requestConsumer).failed(httpex); Mockito.verify(this.requestConsumer).close(); Mockito.verify(this.responseProducer).failed(httpex); Mockito.verify(this.responseProducer).close(); } @Test public void testBasicRequest() throws Exception { final State state = new State(); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); Mockito.when(this.requestConsumer.getException()).thenReturn(null); final Object data = new Object(); Mockito.when(this.requestConsumer.getResult()).thenReturn(data); this.protocolHandler.requestReceived(this.conn); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final Incoming incoming = state.getIncoming(); Assert.assertNull(incoming); final ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(HttpContext.class); Mockito.verify(this.httpProcessor).process(Mockito.eq(request), argumentCaptor.capture()); final HttpContext exchangeContext = argumentCaptor.getValue(); Assert.assertNotNull(exchangeContext); Assert.assertSame(request, exchangeContext.getAttribute(HttpCoreContext.HTTP_REQUEST)); Assert.assertSame(this.conn, exchangeContext.getAttribute(HttpCoreContext.HTTP_CONNECTION)); Mockito.verify(this.requestConsumer).requestReceived(request); Mockito.verify(this.requestConsumer).requestCompleted(exchangeContext); Mockito.verify(this.conn).requestOutput(); final PipelineEntry entry = state.getPipeline().poll(); Assert.assertNotNull(entry); Assert.assertSame(request, entry.getRequest()); Assert.assertSame(requestHandler, entry.getHandler()); Assert.assertNotNull(entry.getResult()); Assert.assertNull(entry.getException()); } @Test public void testRequestPipelineIfResponseInitiated() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.INIT); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); Mockito.when(this.requestConsumer.getException()).thenReturn(null); final Object data = new Object(); Mockito.when(this.requestConsumer.getResult()).thenReturn(data); this.protocolHandler.requestReceived(this.conn); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.INIT, state.getResponseState()); final Incoming incoming = state.getIncoming(); Assert.assertNull(incoming); Mockito.verify(this.requestConsumer).requestReceived(request); Mockito.verify(this.requestConsumer).requestCompleted(Mockito.any()); Mockito.verify(this.requestHandler, Mockito.never()).handle( Mockito.any(), Mockito.any(HttpAsyncExchange.class), Mockito.any(HttpContext.class)); Assert.assertFalse(state.getPipeline().isEmpty()); final PipelineEntry entry = state.getPipeline().remove(); Assert.assertSame(request, entry.getRequest()); Assert.assertSame(data, entry.getResult()); } @Test public void testRequestPipelineIfPipelineNotEmpty() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.READY); final Queue pipeline = state.getPipeline(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest pipelinedRequest = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final PipelineEntry entry = new PipelineEntry(pipelinedRequest, pipelinedRequest, null, requestHandler, exchangeContext); pipeline.add(entry); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); Mockito.when(this.requestConsumer.getException()).thenReturn(null); final Object data = new Object(); Mockito.when(this.requestConsumer.getResult()).thenReturn(data); this.protocolHandler.requestReceived(this.conn); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final Incoming incoming = state.getIncoming(); Assert.assertNull(incoming); Mockito.verify(this.requestConsumer).requestReceived(request); Mockito.verify(this.requestConsumer).requestCompleted(Mockito.any()); Mockito.verify(this.requestHandler, Mockito.never()).handle( Mockito.any(), Mockito.any(HttpAsyncExchange.class), Mockito.any(HttpContext.class)); Assert.assertFalse(state.getPipeline().isEmpty()); final PipelineEntry entry1 = state.getPipeline().remove(); Assert.assertSame(entry, entry1); final PipelineEntry entry2 = state.getPipeline().remove(); Assert.assertSame(request, entry2.getRequest()); Assert.assertSame(data, entry2.getResult()); } @Test public void testRequestNoMatchingHandler() throws Exception { final State state = new State(); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/stuff", HttpVersion.HTTP_1_1); request.setEntity(new NStringEntity("stuff")); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); this.protocolHandler.requestReceived(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final Incoming incoming = state.getIncoming(); Assert.assertNotNull(incoming); Assert.assertSame(request, incoming.getRequest()); Assert.assertTrue(incoming.getHandler() instanceof NullRequestHandler); } @Test public void testEntityEnclosingRequest() throws Exception { final State state = new State(); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); this.protocolHandler.requestReceived(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final Incoming incoming = state.getIncoming(); Assert.assertNotNull(incoming); Assert.assertSame(request, incoming.getRequest()); Assert.assertSame(this.requestHandler, incoming.getHandler()); Assert.assertSame(this.requestConsumer, incoming.getConsumer()); final HttpContext exchangeContext = incoming.getContext(); Assert.assertNotNull(exchangeContext); Assert.assertSame(request, exchangeContext.getAttribute(HttpCoreContext.HTTP_REQUEST)); Assert.assertSame(this.conn, exchangeContext.getAttribute(HttpCoreContext.HTTP_CONNECTION)); Mockito.verify(this.httpProcessor).process(request, exchangeContext); Mockito.verify(this.requestConsumer).requestReceived(request); Mockito.verify(this.conn, Mockito.never()).suspendInput(); } @Test public void testEntityEnclosingRequestContinueWithoutVerification() throws Exception { final State state = new State(); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); this.protocolHandler.requestReceived(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final Incoming incoming = state.getIncoming(); Assert.assertNotNull(incoming); Assert.assertSame(request, incoming.getRequest()); Assert.assertSame(this.requestHandler, incoming.getHandler()); Assert.assertSame(this.requestConsumer, incoming.getConsumer()); final HttpContext exchangeContext = incoming.getContext(); Assert.assertNotNull(exchangeContext); Assert.assertSame(request, exchangeContext.getAttribute(HttpCoreContext.HTTP_REQUEST)); Assert.assertSame(this.conn, exchangeContext.getAttribute(HttpCoreContext.HTTP_CONNECTION)); Mockito.verify(this.httpProcessor).process(request, exchangeContext); Mockito.verify(this.requestConsumer).requestReceived(request); Mockito.verify(this.conn, Mockito.never()).suspendInput(); Mockito.verify(this.conn).submitResponse(Mockito.argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { final int status = ((HttpResponse) argument).getStatusLine().getStatusCode(); return status == 100; } })); } @Test public void testEntityEnclosingRequestExpectationVerification() throws Exception { final HttpAsyncExpectationVerifier expectationVerifier = Mockito.mock(HttpAsyncExpectationVerifier.class); this.protocolHandler = new HttpAsyncService( this.httpProcessor, this.reuseStrategy, this.responseFactory, this.handlerResolver, expectationVerifier); final State state = new State(); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); this.protocolHandler.requestReceived(this.conn); Assert.assertEquals(MessageState.ACK_EXPECTED, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final Incoming incoming = state.getIncoming(); Assert.assertNotNull(incoming); Assert.assertSame(request, incoming.getRequest()); Assert.assertSame(this.requestHandler, incoming.getHandler()); Assert.assertSame(this.requestConsumer, incoming.getConsumer()); final HttpContext exchangeContext = incoming.getContext(); Assert.assertNotNull(exchangeContext); Assert.assertSame(request, exchangeContext.getAttribute(HttpCoreContext.HTTP_REQUEST)); Assert.assertSame(this.conn, exchangeContext.getAttribute(HttpCoreContext.HTTP_CONNECTION)); Mockito.verify(this.httpProcessor).process(request, exchangeContext); Mockito.verify(this.requestConsumer).requestReceived(request); Mockito.verify(this.conn).suspendInput(); Mockito.verify(expectationVerifier).verify( Mockito.any(HttpAsyncExchange.class), Mockito.eq(exchangeContext)); } @Test public void testRequestExpectationFailed() throws Exception { final State state = new State(); state.setRequestState(MessageState.ACK_EXPECTED); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpContext exchangeContext = new BasicHttpContext(); final HttpAsyncExchange httpexchanage = protocolHandler.new HttpAsyncExchangeImpl( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"), state, this.conn, exchangeContext); Assert.assertFalse(httpexchanage.isCompleted()); httpexchanage.submitResponse(this.responseProducer); Assert.assertTrue(httpexchanage.isCompleted()); Assert.assertEquals(MessageState.ACK_EXPECTED, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final Outgoing outgoing = state.getOutgoing(); Assert.assertNotNull(outgoing); Assert.assertSame(this.responseProducer, outgoing.getProducer()); Mockito.verify(this.conn).requestOutput(); try { httpexchanage.submitResponse(); Assert.fail("IllegalStateException expected"); } catch (final IllegalStateException ex) { } } @Test(expected=IllegalArgumentException.class) public void testRequestExpectationFailedInvalidResponseProducer() throws Exception { final State state = new State(); state.setRequestState(MessageState.ACK_EXPECTED); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpContext exchangeContext = new BasicHttpContext(); final HttpAsyncExchange httpexchanage = protocolHandler.new HttpAsyncExchangeImpl( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"), state, this.conn, exchangeContext); httpexchanage.submitResponse(null); } @Test public void testRequestExpectationNoHandshakeIfResponseInitiated() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.INIT); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); this.protocolHandler.requestReceived(this.conn); Mockito.verify(this.requestConsumer).requestReceived(request); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.INIT, state.getResponseState()); } @Test public void testRequestExpectationNoHandshakeIfPipelineNotEmpty() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.READY); final Queue pipeline = state.getPipeline(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest pipelinedRequest = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final PipelineEntry entry = new PipelineEntry(pipelinedRequest, pipelinedRequest, null, requestHandler, exchangeContext); pipeline.add(entry); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); this.protocolHandler.requestReceived(this.conn); Mockito.verify(this.requestConsumer).requestReceived(request); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); } @Test public void testRequestExpectationNoHandshakeIfMoreInputAvailable() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); state.setResponseState(MessageState.READY); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); this.conn = Mockito.mock(NHttpServerConnection.class, Mockito.withSettings().extraInterfaces(SessionBufferStatus.class)); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); Mockito.when(this.conn.getContext()).thenReturn(this.connContext); Mockito.when(this.conn.getHttpRequest()).thenReturn(request); Mockito.when(this.requestHandler.processRequest( Mockito.eq(request), Mockito.any(HttpContext.class))).thenReturn(this.requestConsumer); Mockito.when(((SessionBufferStatus) this.conn).hasBufferedInput()).thenReturn(Boolean.TRUE); this.protocolHandler.requestReceived(this.conn); Mockito.verify(this.requestConsumer).requestReceived(request); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); } @Test public void testRequestContinue() throws Exception { final State state = new State(); state.setRequestState(MessageState.ACK_EXPECTED); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpContext exchangeContext = new BasicHttpContext(); final HttpAsyncExchange httpexchanage = protocolHandler.new HttpAsyncExchangeImpl( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Continue"), state, this.conn, exchangeContext); Assert.assertFalse(httpexchanage.isCompleted()); httpexchanage.submitResponse(); Assert.assertTrue(httpexchanage.isCompleted()); final Outgoing outgoing = state.getOutgoing(); Assert.assertNotNull(outgoing); final HttpAsyncResponseProducer responseProducer = outgoing.getProducer(); Assert.assertNotNull(responseProducer); Assert.assertEquals(MessageState.ACK_EXPECTED, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final HttpResponse response = responseProducer.generateResponse(); Assert.assertEquals(HttpStatus.SC_CONTINUE, response.getStatusLine().getStatusCode()); Mockito.verify(this.conn).requestOutput(); try { httpexchanage.submitResponse(this.responseProducer); Assert.fail("IllegalStateException expected"); } catch (final IllegalStateException ex) { } } @Test public void testRequestContent() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); state.setRequestState(MessageState.BODY_STREAM); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.decoder.isCompleted()).thenReturn(Boolean.FALSE); this.protocolHandler.inputReady(conn, this.decoder); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.requestConsumer).consumeContent(this.decoder, this.conn); Mockito.verify(this.conn, Mockito.never()).suspendInput(); } @Test public void testRequestContentCompleted() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); state.setRequestState(MessageState.BODY_STREAM); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.decoder.isCompleted()).thenReturn(Boolean.TRUE); Mockito.when(this.requestConsumer.getException()).thenReturn(null); final Object data = new Object(); Mockito.when(this.requestConsumer.getResult()).thenReturn(data); this.protocolHandler.inputReady(conn, this.decoder); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.requestConsumer).consumeContent(this.decoder, this.conn); Mockito.verify(this.requestConsumer).requestCompleted(exchangeContext); Mockito.verify(this.conn).requestOutput(); final PipelineEntry entry = state.getPipeline().poll(); Assert.assertNotNull(entry); Assert.assertSame(request, entry.getRequest()); Assert.assertSame(requestHandler, entry.getHandler()); Assert.assertNotNull(entry.getResult()); Assert.assertNull(entry.getException()); } @Test public void testRequestCompletedWithException() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); state.setRequestState(MessageState.BODY_STREAM); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.decoder.isCompleted()).thenReturn(Boolean.TRUE); Mockito.when(this.requestConsumer.getException()).thenReturn(new HttpException()); Mockito.when(this.requestConsumer.getResult()).thenReturn(null); this.protocolHandler.inputReady(conn, this.decoder); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.requestConsumer).consumeContent(this.decoder, this.conn); Mockito.verify(this.requestConsumer).requestCompleted(exchangeContext); Mockito.verify(this.conn).requestOutput(); final PipelineEntry entry = state.getPipeline().poll(); Assert.assertNotNull(entry); Assert.assertSame(request, entry.getRequest()); Assert.assertSame(requestHandler, entry.getHandler()); Assert.assertNull(entry.getResult()); Assert.assertNotNull(entry.getException()); } @Test public void testBasicResponse() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.COMPLETED); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); state.setResponseState(MessageState.INIT); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); Mockito.when(this.reuseStrategy.keepAlive(response, exchangeContext)).thenReturn(Boolean.TRUE); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.httpProcessor).process(response, exchangeContext); Mockito.verify(this.conn).submitResponse(response); Mockito.verify(this.responseProducer).responseCompleted(exchangeContext); Mockito.verify(this.conn).requestInput(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testBasicResponseWithPipelining() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.COMPLETED); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); response.setEntity(new NStringEntity("stuff")); state.setOutgoing(outgoing); final Queue pipeline = state.getPipeline(); final HttpContext exchangeContext2 = new BasicHttpContext(); final HttpRequest pipelinedRequest = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final PipelineEntry entry = new PipelineEntry(pipelinedRequest, pipelinedRequest, null, requestHandler, exchangeContext2); pipeline.add(entry); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); Mockito.when(this.reuseStrategy.keepAlive(response, exchangeContext)).thenReturn(Boolean.TRUE); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); Mockito.verify(this.httpProcessor).process(response, exchangeContext); Mockito.verify(this.conn).suspendOutput(); Mockito.verify(this.conn).submitResponse(response); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testBasicResponseNoKeepAlive() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.COMPLETED); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); state.setResponseState(MessageState.INIT); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); Mockito.when(this.reuseStrategy.keepAlive(response, exchangeContext)).thenReturn(Boolean.FALSE); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.httpProcessor).process(response, exchangeContext); Mockito.verify(this.conn).submitResponse(response); Mockito.verify(this.responseProducer).responseCompleted(exchangeContext); Mockito.verify(this.conn).close(); } @Test public void testEntityEnclosingResponse() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.COMPLETED); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); state.setResponseState(MessageState.INIT); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); response.setEntity(new NStringEntity("stuff")); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); Assert.assertEquals("[incoming COMPLETED GET / HTTP/1.1; outgoing BODY_STREAM HTTP/1.1 200 OK]", state.toString()); Mockito.verify(this.httpProcessor).process(response, exchangeContext); Mockito.verify(this.conn).submitResponse(response); Mockito.verify(this.responseProducer, Mockito.never()).responseCompleted(exchangeContext); } @Test public void testResponseToHead() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("HEAD", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.COMPLETED); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); state.setResponseState(MessageState.INIT); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); response.setEntity(new NStringEntity("stuff")); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); Mockito.when(this.reuseStrategy.keepAlive(response, exchangeContext)).thenReturn(Boolean.TRUE); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.httpProcessor).process(response, exchangeContext); Mockito.verify(this.conn).submitResponse(response); Mockito.verify(this.responseProducer).responseCompleted(exchangeContext); Mockito.verify(this.conn).requestInput(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testResponseNotModified() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("HEAD", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.COMPLETED); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not modified"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); state.setResponseState(MessageState.INIT); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); response.setEntity(new NStringEntity("stuff")); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); Mockito.when(this.reuseStrategy.keepAlive(response, exchangeContext)).thenReturn(Boolean.TRUE); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.httpProcessor).process(response, exchangeContext); Mockito.verify(this.conn).submitResponse(response); Mockito.verify(this.responseProducer).responseCompleted(exchangeContext); Mockito.verify(this.conn).requestInput(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testResponseContinue() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.ACK_EXPECTED); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_CONTINUE, "Continue"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.BODY_STREAM, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.conn).requestInput(); Mockito.verify(this.conn).submitResponse(Mockito.argThat(new ArgumentMatcher() { @Override public boolean matches(final Object argument) { final int status = ((HttpResponse) argument).getStatusLine().getStatusCode(); return status == 100; } })); } @Test public void testResponseFailedExpectation() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.ACK_EXPECTED); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 417, "Expectation failed"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); response.setEntity(new NStringEntity("stuff")); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); Mockito.verify(this.conn).resetInput(); Mockito.verify(this.httpProcessor).process(response, exchangeContext); Mockito.verify(this.conn).submitResponse(response); Mockito.verify(this.responseProducer, Mockito.never()).responseCompleted(exchangeContext); } @Test public void testResponsePipelinedEmpty() throws Exception { final State state = new State(); state.setRequestState(MessageState.READY); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); Assert.assertNull(state.getOutgoing()); Mockito.verify(conn).suspendOutput(); Mockito.verifyNoMoreInteractions(requestHandler); } @Test public void testResponseHandlePipelinedRequest() throws Exception { final State state = new State(); final Queue pipeline = state.getPipeline(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final PipelineEntry entry = new PipelineEntry(request, request, null, requestHandler, exchangeContext); pipeline.add(entry); state.setRequestState(MessageState.READY); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.INIT, state.getResponseState()); Assert.assertNull(state.getOutgoing()); final ArgumentCaptor argCaptor = ArgumentCaptor.forClass(HttpAsyncExchange.class); Mockito.verify(this.requestHandler).handle(Mockito.same(request), argCaptor.capture(), Mockito.same(exchangeContext)); final HttpAsyncExchange exchange = argCaptor.getValue(); Assert.assertNotNull(exchange); Assert.assertSame(request, exchange.getRequest()); Assert.assertNotNull(exchange.getResponse()); Assert.assertEquals(200, exchange.getResponse().getStatusLine().getStatusCode()); } @Test public void testResponseHandleFailedPipelinedRequest() throws Exception { final State state = new State(); final Queue pipeline = state.getPipeline(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Exception ex = new Exception("Opppsie"); final PipelineEntry entry = new PipelineEntry(request, null, ex, requestHandler, exchangeContext); pipeline.add(entry); state.setRequestState(MessageState.READY); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); this.protocolHandler.responseReady(this.conn); Assert.assertEquals(MessageState.READY, state.getRequestState()); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); final Outgoing outgoing = state.getOutgoing(); Assert.assertNotNull(outgoing.getProducer()); final HttpResponse response = outgoing.getResponse(); Assert.assertNotNull(response); Assert.assertEquals(500, response.getStatusLine().getStatusCode()); Mockito.verify(this.requestHandler, Mockito.never()).handle(Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(this.conn).submitResponse(Mockito.same(response)); } @Test(expected=HttpException.class) public void testInvalidResponseStatus() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.INIT); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 112, "Something stupid"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); Mockito.when(this.conn.isResponseSubmitted()).thenReturn(Boolean.FALSE); this.protocolHandler.responseReady(this.conn); } @Test(expected=HttpException.class) public void testInvalidResponseStatusToExpection() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); state.setRequestState(MessageState.ACK_EXPECTED); state.setResponseState(MessageState.READY); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.setEntity(new NStringEntity("stuff")); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.responseProducer.generateResponse()).thenReturn(response); Mockito.when(this.conn.isResponseSubmitted()).thenReturn(Boolean.FALSE); this.protocolHandler.responseReady(this.conn); } @Test public void testResponseTrigger() throws Exception { final State state = new State(); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.READY); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpContext exchangeContext = new BasicHttpContext(); final HttpAsyncExchange httpexchanage = protocolHandler.new HttpAsyncExchangeImpl( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"), state, this.conn, exchangeContext); Assert.assertFalse(httpexchanage.isCompleted()); httpexchanage.submitResponse(this.responseProducer); Assert.assertTrue(httpexchanage.isCompleted()); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); Assert.assertEquals(MessageState.READY, state.getResponseState()); final Outgoing outgoing = state.getOutgoing(); Assert.assertNotNull(outgoing); Assert.assertSame(this.responseProducer, outgoing.getProducer()); Mockito.verify(this.conn).requestOutput(); try { httpexchanage.submitResponse(Mockito.mock(HttpAsyncResponseProducer.class)); Assert.fail("IllegalStateException expected"); } catch (final IllegalStateException ex) { } } @Test(expected=IllegalArgumentException.class) public void testResponseTriggerInvalidResponseProducer() throws Exception { final State state = new State(); state.setRequestState(MessageState.ACK_EXPECTED); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); final HttpContext exchangeContext = new BasicHttpContext(); final HttpAsyncExchange httpexchanage = protocolHandler.new HttpAsyncExchangeImpl( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"), state, this.conn, exchangeContext); httpexchanage.submitResponse(null); } @Test public void testResponseContent() throws Exception { final State state = new State(); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.BODY_STREAM); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.setEntity(new NStringEntity("stuff")); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.encoder.isCompleted()).thenReturn(Boolean.FALSE); this.protocolHandler.outputReady(conn, this.encoder); Assert.assertEquals(MessageState.COMPLETED, state.getRequestState()); Assert.assertEquals(MessageState.BODY_STREAM, state.getResponseState()); Mockito.verify(this.responseProducer).produceContent(this.encoder, this.conn); Mockito.verify(this.conn, Mockito.never()).requestInput(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testResponseContentCompleted() throws Exception { final State state = new State(); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.BODY_STREAM); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.setEntity(new NStringEntity("stuff")); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.encoder.isCompleted()).thenReturn(true); Mockito.when(this.reuseStrategy.keepAlive(response, exchangeContext)).thenReturn(Boolean.TRUE); this.protocolHandler.outputReady(conn, this.encoder); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.responseProducer).produceContent(this.encoder, this.conn); Mockito.verify(this.responseProducer).responseCompleted(exchangeContext); Mockito.verify(this.conn).requestInput(); Mockito.verify(this.conn, Mockito.never()).close(); } @Test public void testResponseContentCompletedNoKeepAlive() throws Exception { final State state = new State(); state.setRequestState(MessageState.COMPLETED); state.setResponseState(MessageState.BODY_STREAM); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.setEntity(new NStringEntity("stuff")); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.encoder.isCompleted()).thenReturn(true); Mockito.when(this.reuseStrategy.keepAlive(response, exchangeContext)).thenReturn(Boolean.FALSE); this.protocolHandler.outputReady(conn, this.encoder); Assert.assertEquals(MessageState.READY, state.getResponseState()); Mockito.verify(this.responseProducer).produceContent(this.encoder, this.conn); Mockito.verify(this.responseProducer).responseCompleted(exchangeContext); Mockito.verify(this.conn, Mockito.never()).requestInput(); Mockito.verify(this.conn).close(); } @Test public void testEndOfInput() throws Exception { Mockito.when(this.conn.getSocketTimeout()).thenReturn(1000); this.protocolHandler.endOfInput(this.conn); Mockito.verify(this.conn, Mockito.never()).setSocketTimeout(Mockito.anyInt()); Mockito.verify(this.conn).close(); } @Test public void testEndOfInputNoTimeout() throws Exception { Mockito.when(this.conn.getSocketTimeout()).thenReturn(0); this.protocolHandler.endOfInput(this.conn); Mockito.verify(this.conn).setSocketTimeout(1000); Mockito.verify(this.conn).close(); } @Test public void testTimeoutActiveConnection() throws Exception { final State state = new State(); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.conn.getStatus()).thenReturn(NHttpClientConnection.ACTIVE, NHttpClientConnection.CLOSED); this.protocolHandler.timeout(this.conn); Mockito.verify(this.conn).close(); Mockito.verify(this.conn, Mockito.never()).setSocketTimeout(Mockito.anyInt()); } @Test public void testTimeoutActiveConnectionBufferedData() throws Exception { final State state = new State(); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.conn.getStatus()).thenReturn(NHttpClientConnection.ACTIVE, NHttpClientConnection.CLOSING); this.protocolHandler.timeout(this.conn); Mockito.verify(this.conn).close(); Mockito.verify(this.conn).setSocketTimeout(250); } @Test public void testTimeoutClosingConnection() throws Exception { final State state = new State(); final HttpContext exchangeContext = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Incoming incoming = new Incoming( request, this.requestHandler, this.requestConsumer, exchangeContext); state.setIncoming(incoming); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final Outgoing outgoing = new Outgoing( request, response, this.responseProducer, exchangeContext); state.setOutgoing(outgoing); this.connContext.setAttribute(HttpAsyncService.HTTP_EXCHANGE_STATE, state); Mockito.when(this.conn.getStatus()).thenReturn(NHttpClientConnection.CLOSING); this.protocolHandler.timeout(this.conn); Mockito.verify(this.conn).shutdown(); Mockito.verify(this.requestConsumer).failed(Mockito.any(SocketTimeoutException.class)); Mockito.verify(this.requestConsumer).close(); Mockito.verify(this.responseProducer).failed(Mockito.any(SocketTimeoutException.class)); Mockito.verify(this.responseProducer).close(); } } ././@LongLink0100644 0000000 0000000 00000000173 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncClientExchangeHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncClie0100644 0000000 0000000 00000032423 12613456023 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.nio.protocol; import java.util.concurrent.ExecutionException; import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpRequest; import org.apache.http.HttpVersion; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class TestBasicAsyncClientExchangeHandler { private HttpAsyncRequestProducer requestProducer; private HttpAsyncResponseConsumer responseConsumer; private HttpContext context; private HttpProcessor httpProcessor; private NHttpClientConnection conn; private ConnectionReuseStrategy reuseStrategy; private BasicAsyncClientExchangeHandler exchangeHandler; private ContentEncoder encoder; private ContentDecoder decoder; @SuppressWarnings("unchecked") @Before public void setUp() throws Exception { this.requestProducer = Mockito.mock(HttpAsyncRequestProducer.class); this.responseConsumer = Mockito.mock(HttpAsyncResponseConsumer.class); this.context = new BasicHttpContext(); this.conn = Mockito.mock(NHttpClientConnection.class); this.httpProcessor = Mockito.mock(HttpProcessor.class); this.reuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); this.exchangeHandler = new BasicAsyncClientExchangeHandler( this.requestProducer, this.responseConsumer, null, this.context, this.conn, this.httpProcessor, this.reuseStrategy); this.encoder = Mockito.mock(ContentEncoder.class); this.decoder = Mockito.mock(ContentDecoder.class); } @After public void tearDown() throws Exception { } @Test public void testInvalidExecution() throws Exception { try { new BasicAsyncClientExchangeHandler( null, this.responseConsumer, null, this.context, this.conn, this.httpProcessor, this.reuseStrategy); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { new BasicAsyncClientExchangeHandler( this.requestProducer, null, null, this.context, this.conn, this.httpProcessor, this.reuseStrategy); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { new BasicAsyncClientExchangeHandler( this.requestProducer, this.responseConsumer, null, null, this.conn, this.httpProcessor, this.reuseStrategy); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { new BasicAsyncClientExchangeHandler( this.requestProducer, this.responseConsumer, null, this.context, null, this.httpProcessor, this.reuseStrategy); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { new BasicAsyncClientExchangeHandler( this.requestProducer, this.responseConsumer, null, this.context, this.conn, null, this.reuseStrategy); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } } @Test public void testClose() throws Exception { Assert.assertFalse(this.exchangeHandler.getFuture().isCancelled()); this.exchangeHandler.close(); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.responseConsumer).close(); Assert.assertTrue(this.exchangeHandler.getFuture().isCancelled()); } @Test public void testGenerateRequest() throws Exception { final BasicHttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); Mockito.when(this.requestProducer.generateRequest()).thenReturn(request); final HttpRequest result = this.exchangeHandler.generateRequest(); Assert.assertSame(request, result); Mockito.verify(this.requestProducer).generateRequest(); Assert.assertSame(request, this.context.getAttribute(HttpCoreContext.HTTP_REQUEST)); Assert.assertSame(this.conn, this.context.getAttribute(HttpCoreContext.HTTP_CONNECTION)); Mockito.verify(this.httpProcessor).process(request, this.context); } @Test public void testProduceContent() throws Exception { Mockito.when(this.encoder.isCompleted()).thenReturn(false); this.exchangeHandler.produceContent(this.encoder, this.conn); Mockito.verify(this.requestProducer).produceContent(this.encoder, this.conn); } @Test public void testProduceContentCompleted() throws Exception { Mockito.when(this.encoder.isCompleted()).thenReturn(true); this.exchangeHandler.produceContent(this.encoder, this.conn); Mockito.verify(this.requestProducer).produceContent(this.encoder, this.conn); } @Test public void testRequestCompleted() throws Exception { this.exchangeHandler.requestCompleted(); Mockito.verify(this.requestProducer).requestCompleted(this.context); } @Test public void testResponseReceived() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); this.exchangeHandler.responseReceived(response); Mockito.verify(this.responseConsumer).responseReceived(response); Assert.assertSame(response, this.context.getAttribute(HttpCoreContext.HTTP_RESPONSE)); Mockito.verify(this.httpProcessor).process(response, this.context); } @Test public void testConsumeContent() throws Exception { this.exchangeHandler.consumeContent(this.decoder, this.conn); Mockito.verify(this.responseConsumer).consumeContent(this.decoder, this.conn); } @Test public void testFailed() throws Exception { final Exception ooopsie = new Exception(); this.exchangeHandler.failed(ooopsie); Mockito.verify(this.requestProducer).failed(ooopsie); Mockito.verify(this.responseConsumer).failed(ooopsie); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.responseConsumer).close(); try { this.exchangeHandler.getFuture().get(); } catch (final ExecutionException ex) { Assert.assertSame(ooopsie, ex.getCause()); } } @Test public void testFailedAfterRequest() throws Exception { final Exception ooopsie = new Exception(); this.exchangeHandler.requestCompleted(); this.exchangeHandler.failed(ooopsie); Mockito.verify(this.requestProducer, Mockito.never()).failed(ooopsie); Mockito.verify(this.responseConsumer).failed(ooopsie); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.responseConsumer).close(); try { this.exchangeHandler.getFuture().get(); } catch (final ExecutionException ex) { Assert.assertSame(ooopsie, ex.getCause()); } } @Test public void testFailedwithException() throws Exception { final Exception ooopsie = new Exception(); Mockito.doThrow(new RuntimeException()).when(this.responseConsumer).failed(ooopsie); try { this.exchangeHandler.failed(ooopsie); Assert.fail("RuntimeException expected"); } catch (final RuntimeException ex) { Mockito.verify(this.requestProducer).close(); Mockito.verify(this.responseConsumer).close(); try { this.exchangeHandler.getFuture().get(); } catch (final ExecutionException exex) { Assert.assertSame(ooopsie, exex.getCause()); } } } @Test public void testCancel() throws Exception { this.exchangeHandler.cancel(); Mockito.verify(this.responseConsumer).cancel(); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.responseConsumer).close(); Assert.assertTrue(this.exchangeHandler.getFuture().isCancelled()); } @Test public void testResponseCompleted() throws Exception { final Object obj = new Object(); Mockito.when(this.responseConsumer.getResult()).thenReturn(obj); this.exchangeHandler.responseCompleted(); Mockito.verify(this.responseConsumer).responseCompleted(this.context); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.responseConsumer).close(); final Object result = this.exchangeHandler.getFuture().get(); Assert.assertSame(obj, result); } @Test public void testResponseFailure() throws Exception { final Exception ooopsie = new Exception(); Mockito.when(this.responseConsumer.getException()).thenReturn(ooopsie); this.exchangeHandler.responseCompleted(); Mockito.verify(this.responseConsumer).responseCompleted(this.context); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.responseConsumer).close(); try { this.exchangeHandler.getFuture().get(); } catch (final ExecutionException exex) { Assert.assertSame(ooopsie, exex.getCause()); } } @Test public void testResponseCompletedWithException() throws Exception { Mockito.doThrow(new RuntimeException()).when(this.responseConsumer).responseCompleted(this.context); try { this.exchangeHandler.responseCompleted(); Assert.fail("RuntimeException expected"); } catch (final RuntimeException ex) { Mockito.verify(this.requestProducer).close(); Mockito.verify(this.responseConsumer).close(); try { this.exchangeHandler.getFuture().get(); Assert.fail("ExecutionException expected"); } catch (final ExecutionException exex) { } } } @Test public void testResponseNoKeepAlive() throws Exception { final Object obj = new Object(); Mockito.when(this.responseConsumer.getResult()).thenReturn(obj); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(reuseStrategy.keepAlive(response, this.context)).thenReturn(Boolean.FALSE); this.exchangeHandler.responseReceived(response); this.exchangeHandler.responseCompleted(); Mockito.verify(this.conn).close(); } @Test public void testInputTerminated() throws Exception { this.exchangeHandler.inputTerminated(); Mockito.verify(this.responseConsumer).failed(Mockito.any()); try { this.exchangeHandler.getFuture().get(); Assert.fail("ExecutionException expected"); } catch (final ExecutionException exex) { } } @Test public void testIsDone() throws Exception { this.exchangeHandler.isDone(); Mockito.verify(this.responseConsumer).isDone(); } } ././@LongLink0100644 0000000 0000000 00000000165 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncRequestConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncRequ0100644 0000000 0000000 00000007250 12613456023 032451 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.entity.StringEntity; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class TestBasicAsyncRequestConsumer { private BasicAsyncRequestConsumer consumer; @Mock private HttpEntityEnclosingRequest request; @Mock private HttpContext context; @Mock private ContentDecoder decoder; @Mock private IOControl ioctrl; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); consumer = Mockito.spy(new BasicAsyncRequestConsumer()); } @After public void tearDown() throws Exception { } @Test public void testRequestProcessing() throws Exception { when(request.getEntity()).thenReturn(new StringEntity("stuff")); consumer.requestReceived(request); consumer.consumeContent(decoder, ioctrl); consumer.requestCompleted(context); verify(consumer).releaseResources(); verify(consumer).buildResult(context); Assert.assertTrue(consumer.isDone()); Assert.assertSame(request, consumer.getResult()); consumer.requestCompleted(context); verify(consumer, times(1)).releaseResources(); verify(consumer, times(1)).buildResult(context); } @Test public void testResponseProcessingWithException() throws Exception { when(request.getEntity()).thenReturn(new StringEntity("stuff")); final RuntimeException ooopsie = new RuntimeException(); when(consumer.buildResult(context)).thenThrow(ooopsie); consumer.requestReceived(request); consumer.consumeContent(decoder, ioctrl); consumer.requestCompleted(context); verify(consumer).releaseResources(); Assert.assertTrue(consumer.isDone()); Assert.assertSame(ooopsie, consumer.getException()); } @Test public void testClose() throws Exception { consumer.close(); verify(consumer).releaseResources(); Assert.assertTrue(consumer.isDone()); consumer.close(); verify(consumer, times(1)).releaseResources(); } } ././@LongLink0100644 0000000 0000000 00000000174 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestUriHttpAsyncRequestHandlerMapper.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestUriHttpAsyncRe0100644 0000000 0000000 00000010344 12613456023 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.nio.protocol; import org.apache.http.HttpRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.protocol.UriPatternMatcher; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestUriHttpAsyncRequestHandlerMapper { @Test public void testRegisterUnregister() throws Exception { final HttpAsyncRequestHandler h = Mockito.mock(HttpAsyncRequestHandler.class); final UriPatternMatcher> matcher = Mockito.spy( new UriPatternMatcher>()); final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(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 UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(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 UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(); registry.register(null, null); } @Test(expected=IllegalArgumentException.class) public void testLookupNull() throws Exception { final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(); registry.register(null, null); } @Test public void testWildCardMatchingWithQuery() throws Exception { final HttpAsyncRequestHandler h1 = Mockito.mock(HttpAsyncRequestHandler.class); final HttpAsyncRequestHandler h2 = Mockito.mock(HttpAsyncRequestHandler.class); final HttpAsyncRequestHandler def = Mockito.mock(HttpAsyncRequestHandler.class); final UriPatternMatcher> matcher = Mockito.spy( new UriPatternMatcher>()); final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(matcher); registry.register("*", def); registry.register("*.view", h1); registry.register("*.form", h2); HttpAsyncRequestHandler 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); } } ././@LongLink0100644 0000000 0000000 00000000166 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncResponseProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestBasicAsyncResp0100644 0000000 0000000 00000006246 12613456023 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.nio.protocol; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.http.HttpResponse; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.entity.HttpAsyncContentProducer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class TestBasicAsyncResponseProducer { private BasicAsyncResponseProducer producer; @Mock private HttpAsyncContentProducer contentProducer; @Mock private HttpResponse response; @Mock private ContentEncoder encoder; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); producer = new BasicAsyncResponseProducer(response, contentProducer); } @After public void tearDown() throws Exception { } @Test(expected=IllegalArgumentException.class) public void testNullTargetArgConstructor() throws Exception { producer = new BasicAsyncResponseProducer(null); } @Test public void testGenerateRequest() { final HttpResponse res = producer.generateResponse(); Assert.assertSame(response, res); } @SuppressWarnings("boxing") @Test public void testProduceContentEncoderCompleted() throws Exception { when(encoder.isCompleted()).thenReturn(Boolean.TRUE); producer.produceContent(encoder, null); verify(contentProducer, times(1)).close(); } @SuppressWarnings("boxing") @Test public void testProduceContentEncoderNotCompleted() throws Exception { when(encoder.isCompleted()).thenReturn(Boolean.FALSE); producer.produceContent(encoder, null); verify(contentProducer, never()).close(); } @Test public void testClose() throws Exception { producer.close(); verify(contentProducer, times(1)).close(); } } ././@LongLink0100644 0000000 0000000 00000000161 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestErrorResponseProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestErrorResponseP0100644 0000000 0000000 00000005341 12613456023 032524 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; import org.apache.http.protocol.HTTP; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestErrorResponseProducer { private ErrorResponseProducer erp; private HttpResponse response; private HttpEntity entity; @Before public void setUp() throws Exception { response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); entity = new StringEntity("stuff"); } @After public void tearDown() throws Exception { } @Test public void testGenerateResponseKeepAlive() { erp = new ErrorResponseProducer(response, entity, true); final HttpResponse res = erp.generateResponse(); Assert.assertEquals(HTTP.CONN_KEEP_ALIVE, res.getFirstHeader(HTTP.CONN_DIRECTIVE).getValue()); Assert.assertEquals(entity, res.getEntity()); Assert.assertEquals(200, res.getStatusLine().getStatusCode()); } @Test public void testGenerateResponseClose() { erp = new ErrorResponseProducer(response, entity, false); final HttpResponse res = erp.generateResponse(); Assert.assertEquals(HTTP.CONN_CLOSE, res.getFirstHeader(HTTP.CONN_DIRECTIVE).getValue()); Assert.assertEquals(entity, res.getEntity()); Assert.assertEquals(200, res.getStatusLine().getStatusCode()); } } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestHttpAsyncRequester.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/protocol/TestHttpAsyncReque0100644 0000000 0000000 00000037246 12613456023 032524 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpHost; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.pool.BasicNIOPoolEntry; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.protocol.HttpAsyncRequester.ConnRequestCallback; import org.apache.http.pool.ConnPool; import org.apache.http.pool.PoolEntry; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; public class TestHttpAsyncRequester { private HttpProcessor httpProcessor; private ConnectionReuseStrategy reuseStrategy; private HttpAsyncRequester requester; private HttpContext exchangeContext; private HttpContext connContext; private HttpAsyncRequestProducer requestProducer; private HttpAsyncResponseConsumer responseConsumer; private NHttpClientConnection conn; private FutureCallback callback; private ConnPool> connPool; @SuppressWarnings("unchecked") @Before public void setUp() throws Exception { this.httpProcessor = Mockito.mock(HttpProcessor.class); this.reuseStrategy = Mockito.mock(ConnectionReuseStrategy.class); this.requester = new HttpAsyncRequester(this.httpProcessor, this.reuseStrategy); this.exchangeContext = new BasicHttpContext(); this.requestProducer = Mockito.mock(HttpAsyncRequestProducer.class); this.responseConsumer = Mockito.mock(HttpAsyncResponseConsumer.class); this.conn = Mockito.mock(NHttpClientConnection.class); this.callback = Mockito.mock(FutureCallback.class); this.connContext = new BasicHttpContext(); this.connPool = Mockito.mock(ConnPool.class); Mockito.when(this.conn.getContext()).thenReturn(this.connContext); } @After public void tearDown() throws Exception { } @Test public void testInvalidExecution() throws Exception { try { this.requester.execute( null, this.responseConsumer, this.conn); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { this.requester.execute( this.requestProducer, null, this.conn); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { this.requester.execute( this.requestProducer, this.responseConsumer, (NHttpClientConnection) null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { this.requester.execute( this.requestProducer, this.responseConsumer, this.conn, null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { this.requester.execute( null, this.responseConsumer, this.connPool); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { this.requester.execute( this.requestProducer, null, this.connPool); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { this.requester.execute( this.requestProducer, this.responseConsumer, (ConnPool>) null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } try { this.requester.execute( this.requestProducer, this.responseConsumer, this.connPool, null); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ex) { } } @Test public void testSimpleExecute() throws Exception { Mockito.when(this.conn.isOpen()).thenReturn(Boolean.TRUE); final Future future = this.requester.execute( this.requestProducer, this.responseConsumer, this.conn, this.exchangeContext, null); Assert.assertNotNull(future); Assert.assertNotNull(this.connContext.getAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER)); Mockito.verify(this.conn).requestOutput(); } @Test public void testExecuteConnectionClosedUnexpectedly() throws Exception { Mockito.when(this.conn.isOpen()).thenReturn(false); final Future future = this.requester.execute( this.requestProducer, this.responseConsumer, this.conn, this.exchangeContext, null); Assert.assertNotNull(future); Mockito.verify(this.requestProducer).failed(Mockito.any(ConnectionClosedException.class)); Mockito.verify(this.responseConsumer).failed(Mockito.any(ConnectionClosedException.class)); Mockito.verify(this.requestProducer, Mockito.atLeastOnce()).close(); Mockito.verify(this.responseConsumer, Mockito.atLeastOnce()).close(); Assert.assertTrue(future.isDone()); Assert.assertNotNull(future.isDone()); try { future.get(); } catch (final ExecutionException ex) { final Throwable cause = ex.getCause(); Assert.assertNotNull(cause); Assert.assertTrue(cause instanceof ConnectionClosedException); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testPooledConnectionRequestFailed() throws Exception { final HttpHost host = new HttpHost("somehost"); Mockito.when(this.requestProducer.getTarget()).thenReturn(host); final Future future = this.requester.execute( this.requestProducer, this.responseConsumer, this.connPool, this.exchangeContext, this.callback); Assert.assertNotNull(future); final ArgumentCaptor argCaptor = ArgumentCaptor.forClass(FutureCallback.class); Mockito.verify(this.connPool).lease( Mockito.eq(host), Mockito.isNull(), argCaptor.capture()); final ConnRequestCallback connRequestCallback = (ConnRequestCallback) argCaptor.getValue(); final Exception oppsie = new Exception(); connRequestCallback.failed(oppsie); Mockito.verify(this.responseConsumer).failed(oppsie); Mockito.verify(this.callback).failed(oppsie); Mockito.verify(this.responseConsumer).close(); Mockito.verify(this.requestProducer).close(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testPooledConnectionRequestCancelled() throws Exception { final HttpHost host = new HttpHost("somehost"); Mockito.when(this.requestProducer.getTarget()).thenReturn(host); final Future future = this.requester.execute( this.requestProducer, this.responseConsumer, this.connPool, this.exchangeContext, this.callback); Assert.assertNotNull(future); final ArgumentCaptor argCaptor = ArgumentCaptor.forClass(FutureCallback.class); Mockito.verify(this.connPool).lease( Mockito.eq(host), Mockito.isNull(), argCaptor.capture()); final ConnRequestCallback connRequestCallback = (ConnRequestCallback) argCaptor.getValue(); connRequestCallback.cancelled(); Mockito.verify(this.responseConsumer).cancel(); Mockito.verify(this.callback).cancelled(); Mockito.verify(this.responseConsumer).close(); Mockito.verify(this.requestProducer).close(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testPooledConnectionAutoReleaseOnRequestCancel() throws Exception { final HttpHost host = new HttpHost("somehost"); Mockito.when(this.requestProducer.getTarget()).thenReturn(host); final Future future = this.requester.execute( this.requestProducer, this.responseConsumer, this.connPool, this.exchangeContext, this.callback); Assert.assertNotNull(future); final ArgumentCaptor argCaptor = ArgumentCaptor.forClass(FutureCallback.class); Mockito.verify(this.connPool).lease( Mockito.eq(host), Mockito.isNull(), argCaptor.capture()); final ConnRequestCallback connRequestCallback = (ConnRequestCallback) argCaptor.getValue(); future.cancel(true); final BasicNIOPoolEntry entry = new BasicNIOPoolEntry("id", host, this.conn); connRequestCallback.completed(entry); Mockito.verify(this.connPool).release(entry, true); Mockito.verify(this.conn, Mockito.never()).requestOutput(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testPooledRequestExecutionSucceeded() throws Exception { final HttpHost host = new HttpHost("somehost"); Mockito.when(this.requestProducer.getTarget()).thenReturn(host); Mockito.when(this.conn.isOpen()).thenReturn(true); final Future future = this.requester.execute( this.requestProducer, this.responseConsumer, this.connPool, this.exchangeContext, this.callback); Assert.assertNotNull(future); final ArgumentCaptor argCaptor = ArgumentCaptor.forClass(FutureCallback.class); Mockito.verify(this.connPool).lease( Mockito.eq(host), Mockito.isNull(), argCaptor.capture()); final ConnRequestCallback connRequestCallback = (ConnRequestCallback) argCaptor.getValue(); final BasicNIOPoolEntry entry = new BasicNIOPoolEntry("id", host, this.conn); connRequestCallback.completed(entry); final BasicAsyncClientExchangeHandler exchangeHandler = (BasicAsyncClientExchangeHandler) this.connContext.getAttribute( HttpAsyncRequestExecutor.HTTP_HANDLER); Assert.assertNotNull(exchangeHandler); Mockito.verify(this.conn).requestOutput(); final Object result = new Object(); Mockito.when(this.responseConsumer.getResult()).thenReturn(result); exchangeHandler.responseCompleted(); Mockito.verify(this.callback).completed(result); Mockito.verify(this.responseConsumer).close(); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.connPool).release(entry, true); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testPooledRequestExecutionFailed() throws Exception { final HttpHost host = new HttpHost("somehost"); Mockito.when(this.requestProducer.getTarget()).thenReturn(host); Mockito.when(this.conn.isOpen()).thenReturn(true); final Future future = this.requester.execute( this.requestProducer, this.responseConsumer, this.connPool, this.exchangeContext, this.callback); Assert.assertNotNull(future); final ArgumentCaptor argCaptor = ArgumentCaptor.forClass(FutureCallback.class); Mockito.verify(this.connPool).lease( Mockito.eq(host), Mockito.isNull(), argCaptor.capture()); final ConnRequestCallback connRequestCallback = (ConnRequestCallback) argCaptor.getValue(); final BasicNIOPoolEntry entry = new BasicNIOPoolEntry("id", host, this.conn); connRequestCallback.completed(entry); final BasicAsyncClientExchangeHandler exchangeHandler = (BasicAsyncClientExchangeHandler) this.connContext.getAttribute( HttpAsyncRequestExecutor.HTTP_HANDLER); Assert.assertNotNull(exchangeHandler); Mockito.verify(this.conn).requestOutput(); final Exception oppsie = new Exception(); exchangeHandler.failed(oppsie); Mockito.verify(this.responseConsumer).failed(oppsie); Mockito.verify(this.callback).failed(oppsie); Mockito.verify(this.responseConsumer).close(); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.connPool).release(entry, false); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testPooledRequestExecutionCancelled() throws Exception { final HttpHost host = new HttpHost("somehost"); Mockito.when(this.requestProducer.getTarget()).thenReturn(host); Mockito.when(this.conn.isOpen()).thenReturn(true); final Future future = this.requester.execute( this.requestProducer, this.responseConsumer, this.connPool, this.exchangeContext, this.callback); Assert.assertNotNull(future); final ArgumentCaptor argCaptor = ArgumentCaptor.forClass(FutureCallback.class); Mockito.verify(this.connPool).lease( Mockito.eq(host), Mockito.isNull(), argCaptor.capture()); final ConnRequestCallback connRequestCallback = (ConnRequestCallback) argCaptor.getValue(); final BasicNIOPoolEntry entry = new BasicNIOPoolEntry("id", host, this.conn); connRequestCallback.completed(entry); final BasicAsyncClientExchangeHandler exchangeHandler = (BasicAsyncClientExchangeHandler) this.connContext.getAttribute( HttpAsyncRequestExecutor.HTTP_HANDLER); Assert.assertNotNull(exchangeHandler); Mockito.verify(this.conn).requestOutput(); exchangeHandler.cancel(); Mockito.verify(this.responseConsumer).cancel(); Mockito.verify(this.callback).cancelled(); Mockito.verify(this.responseConsumer).close(); Mockito.verify(this.requestProducer).close(); Mockito.verify(this.connPool).release(entry, false); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/pool/0040755 0000000 0000000 00000000000 12613456024 026122 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000151 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/pool/TestRouteSpecificPool.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/pool/TestRouteSpecificPool.0100644 0000000 0000000 00000052474 12613456024 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.nio.pool; import java.io.IOException; import java.net.ConnectException; import java.util.concurrent.ExecutionException; import org.apache.http.concurrent.BasicFuture; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.pool.PoolEntry; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestRouteSpecificPool { static class LocalPoolEntry extends PoolEntry { public LocalPoolEntry(final String route, final IOSession conn) { super(null, route, conn); } @Override public void close() { getConnection().close(); } @Override public boolean isClosed() { return getConnection().isClosed(); } } static class LocalRoutePool extends RouteSpecificPool { public LocalRoutePool() { super("whatever"); } @Override protected LocalPoolEntry createEntry(final String route, final IOSession session) { return new LocalPoolEntry(route, session); } } @Test public void testEmptyPool() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); 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 testSuccessfulConnect() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final IOSession session = Mockito.mock(IOSession.class); final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest.getSession()).thenReturn(session); final BasicFuture future = new BasicFuture(null); pool.addPending(sessionRequest, future); Assert.assertEquals(1, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(1, pool.getPendingCount()); final LocalPoolEntry entry = pool.createEntry(sessionRequest, session); Assert.assertNotNull(entry); Assert.assertSame(session, entry.getConnection()); Assert.assertFalse(future.isDone()); Assert.assertFalse(future.isCancelled()); pool.completed(sessionRequest, entry); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); Assert.assertEquals(1, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(1, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); } @Test public void testFailedConnect() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); final BasicFuture future = new BasicFuture(null); pool.addPending(sessionRequest, future); Assert.assertEquals(1, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(1, pool.getPendingCount()); pool.failed(sessionRequest, new IOException()); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); try { future.get(); Assert.fail("ExecutionException should have been thrown"); } catch (final ExecutionException ex) { Assert.assertTrue(ex.getCause() instanceof IOException); } Assert.assertEquals(0, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); } @Test public void testCancelledConnect() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); final BasicFuture future = new BasicFuture(null); pool.addPending(sessionRequest, future); Assert.assertEquals(1, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(1, pool.getPendingCount()); pool.cancelled(sessionRequest); Assert.assertTrue(future.isDone()); Assert.assertTrue(future.isCancelled()); Assert.assertEquals(0, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); } @Test public void testConnectTimeout() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); final BasicFuture future = new BasicFuture(null); pool.addPending(sessionRequest, future); Assert.assertEquals(1, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(1, pool.getPendingCount()); pool.timeout(sessionRequest); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); try { future.get(); Assert.fail("ExecutionException should have been thrown"); } catch (final ExecutionException ex) { Assert.assertTrue(ex.getCause() instanceof ConnectException); } Assert.assertEquals(0, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); } @Test public void testLeaseRelease() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final IOSession session1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getSession()).thenReturn(session1); final BasicFuture future1 = new BasicFuture(null); pool.addPending(sessionRequest1, future1); final IOSession session2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getSession()).thenReturn(session2); final BasicFuture future2 = new BasicFuture(null); pool.addPending(sessionRequest2, future2); final IOSession session3 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest3 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest3.getSession()).thenReturn(session3); final BasicFuture future3 = new BasicFuture(null); pool.addPending(sessionRequest3, future3); Assert.assertEquals(3, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(3, pool.getPendingCount()); final LocalPoolEntry entry1 = pool.createEntry(sessionRequest1, session1); pool.completed(sessionRequest1, entry1); Assert.assertNotNull(entry1); final LocalPoolEntry entry2 = pool.createEntry(sessionRequest2, session2); pool.completed(sessionRequest2, entry2); Assert.assertNotNull(entry2); final LocalPoolEntry entry3 = pool.createEntry(sessionRequest3, session3); pool.completed(sessionRequest3, entry3); 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.assertSame(entry1, pool.getLastUsed()); Assert.assertEquals(2, pool.getAllocatedCount()); Assert.assertEquals(2, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(0, pool.getPendingCount()); 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 IOSession session1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getSession()).thenReturn(session1); final BasicFuture future1 = new BasicFuture(null); pool.addPending(sessionRequest1, future1); final IOSession session2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getSession()).thenReturn(session2); final BasicFuture future2 = new BasicFuture(null); pool.addPending(sessionRequest2, future2); final IOSession session3 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest3 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest3.getSession()).thenReturn(session3); final BasicFuture future3 = new BasicFuture(null); pool.addPending(sessionRequest3, future3); Assert.assertEquals(3, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(3, pool.getPendingCount()); final LocalPoolEntry entry1 = pool.createEntry(sessionRequest1, session1); pool.completed(sessionRequest1, entry1); Assert.assertNotNull(entry1); final LocalPoolEntry entry2 = pool.createEntry(sessionRequest2, session2); pool.completed(sessionRequest2, entry2); Assert.assertNotNull(entry2); final LocalPoolEntry entry3 = pool.createEntry(sessionRequest3, session3); pool.completed(sessionRequest3, entry3); 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 IOSession session1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getSession()).thenReturn(session1); final BasicFuture future1 = new BasicFuture(null); pool.addPending(sessionRequest1, future1); final IOSession session2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getSession()).thenReturn(session2); final BasicFuture future2 = new BasicFuture(null); pool.addPending(sessionRequest2, future2); final IOSession session3 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest3 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest3.getSession()).thenReturn(session3); final BasicFuture future3 = new BasicFuture(null); pool.addPending(sessionRequest3, future3); final LocalPoolEntry entry1 = pool.createEntry(sessionRequest1, session1); pool.completed(sessionRequest1, entry1); Assert.assertNotNull(entry1); final LocalPoolEntry entry2 = pool.createEntry(sessionRequest2, session2); pool.completed(sessionRequest2, entry2); Assert.assertNotNull(entry2); final LocalPoolEntry entry3 = pool.createEntry(sessionRequest3, session3); pool.completed(sessionRequest3, entry3); Assert.assertNotNull(entry3); 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 IOSession session = Mockito.mock(IOSession.class); final LocalPoolEntry entry = new LocalPoolEntry("whatever", session); pool.free(entry, true); } @Test public void testRemove() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final IOSession session1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getSession()).thenReturn(session1); final BasicFuture future1 = new BasicFuture(null); pool.addPending(sessionRequest1, future1); final IOSession session2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getSession()).thenReturn(session2); final BasicFuture future2 = new BasicFuture(null); pool.addPending(sessionRequest2, future2); final IOSession session3 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest3 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest3.getSession()).thenReturn(session3); final BasicFuture future3 = new BasicFuture(null); pool.addPending(sessionRequest3, future3); Assert.assertEquals(3, pool.getAllocatedCount()); Assert.assertEquals(0, pool.getAvailableCount()); Assert.assertEquals(0, pool.getLeasedCount()); Assert.assertEquals(3, pool.getPendingCount()); final LocalPoolEntry entry1 = pool.createEntry(sessionRequest1, session1); pool.completed(sessionRequest1, entry1); Assert.assertNotNull(entry1); final LocalPoolEntry entry2 = pool.createEntry(sessionRequest2, session2); pool.completed(sessionRequest2, entry2); Assert.assertNotNull(entry2); final LocalPoolEntry entry3 = pool.createEntry(sessionRequest3, session3); pool.completed(sessionRequest3, entry3); 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 testShutdown() throws Exception { final LocalRoutePool pool = new LocalRoutePool(); final IOSession session1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getSession()).thenReturn(session1); final BasicFuture future1 = new BasicFuture(null); pool.addPending(sessionRequest1, future1); final IOSession session2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getSession()).thenReturn(session2); final BasicFuture future2 = new BasicFuture(null); pool.addPending(sessionRequest2, future2); final IOSession session3 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest3 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest3.getSession()).thenReturn(session3); final BasicFuture future3 = new BasicFuture(null); pool.addPending(sessionRequest3, future3); final LocalPoolEntry entry1 = pool.createEntry(sessionRequest1, session1); pool.completed(sessionRequest1, entry1); Assert.assertNotNull(entry1); final LocalPoolEntry entry2 = pool.createEntry(sessionRequest2, session2); pool.completed(sessionRequest2, entry2); Assert.assertNotNull(entry2); pool.free(entry1, true); Assert.assertEquals(3, 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(sessionRequest3).cancel(); Mockito.verify(session2).close(); Mockito.verify(session1).close(); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/pool/TestNIOConnPool.java0100644 0000000 0000000 00000131244 12613456024 031724 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.pool; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.ConnectException; import java.net.UnknownHostException; import java.util.Collections; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.http.concurrent.BasicFuture; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.pool.PoolEntry; import org.apache.http.pool.PoolStats; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestNIOConnPool { static class LocalPoolEntry extends PoolEntry { private boolean closed; public LocalPoolEntry(final String route, final IOSession conn) { super(null, route, conn); } @Override public void close() { if (this.closed) { return; } this.closed = true; getConnection().close(); } @Override public boolean isClosed() { return this.closed; } } static class LocalConnFactory implements NIOConnFactory { @Override public IOSession create(final String route, final IOSession session) throws IOException { return session; } } static class LocalAddressResolver implements SocketAddressResolver { @Override public SocketAddress resolveLocalAddress(final String route) { return null; } @Override public SocketAddress resolveRemoteAddress(final String route) { return InetSocketAddress.createUnresolved(route, 80); } } static class LocalSessionPool extends AbstractNIOConnPool { public LocalSessionPool( final ConnectingIOReactor ioreactor, final int defaultMaxPerRoute, final int maxTotal) { super(ioreactor, new LocalConnFactory(), new LocalAddressResolver(), defaultMaxPerRoute, maxTotal); } public LocalSessionPool( final ConnectingIOReactor ioreactor, final SocketAddressResolver addressResolver, final int defaultMaxPerRoute, final int maxTotal) { super(ioreactor, new LocalConnFactory(), addressResolver, defaultMaxPerRoute, maxTotal); } @Override protected LocalPoolEntry createEntry(final String route, final IOSession session) { return new LocalPoolEntry(route, session); } } @Test public void testEmptyPool() throws Exception { final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); Assert.assertEquals(10, totals.getMax()); Assert.assertEquals(Collections.emptySet(), pool.getRoutes()); final PoolStats stats = pool.getStats("somehost"); Assert.assertEquals(0, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); Assert.assertEquals(0, stats.getPending()); Assert.assertEquals(2, stats.getMax()); Assert.assertEquals("[leased: []][available: []][pending: []]", pool.toString()); } @Test public void testInternalLeaseRequest() throws Exception { final LeaseRequest leaseRequest = new LeaseRequest("somehost", null, 0, 0, new BasicFuture(null)); Assert.assertEquals("[somehost][null]", leaseRequest.toString()); } @Test public void testInvalidConstruction() throws Exception { final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); try { new LocalSessionPool(null, 1, 1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { new LocalSessionPool(ioreactor, -1, 1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { new LocalSessionPool(ioreactor, 1, -1); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } } @Test public void testSuccessfulConnect() throws Exception { final IOSession iosession = Mockito.mock(IOSession.class); final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest.getSession()).thenReturn(iosession); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); final Future future = pool.lease("somehost", null, 100, TimeUnit.MILLISECONDS, null); Mockito.verify(sessionRequest).setConnectTimeout(100); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(1, totals.getPending()); pool.requestCompleted(sessionRequest); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); final LocalPoolEntry entry = future.get(); Assert.assertNotNull(entry); totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(1, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); } @Test public void testFailedConnect() throws Exception { final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest.getException()).thenReturn(new IOException()); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); final Future future = pool.lease("somehost", null); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(1, totals.getPending()); pool.requestFailed(sessionRequest); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); try { future.get(); Assert.fail("ExecutionException should have been thrown"); } catch (final ExecutionException ex) { Assert.assertTrue(ex.getCause() instanceof IOException); } totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); } @Test public void testCencelledConnect() throws Exception { final IOSession iosession = Mockito.mock(IOSession.class); final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest.getSession()).thenReturn(iosession); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest); Mockito.when(ioreactor.getStatus()).thenReturn(IOReactorStatus.ACTIVE); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); final Future future = pool.lease("somehost", null); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(1, totals.getPending()); pool.requestCancelled(sessionRequest); Assert.assertTrue(future.isDone()); Assert.assertTrue(future.isCancelled()); final LocalPoolEntry entry = future.get(); Assert.assertNull(entry); totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); } @Test public void testTimeoutConnect() throws Exception { final IOSession iosession = Mockito.mock(IOSession.class); final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest.getSession()).thenReturn(iosession); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); final Future future = pool.lease("somehost", null); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(1, totals.getPending()); pool.requestTimeout(sessionRequest); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); try { future.get(); Assert.fail("ExecutionException should have been thrown"); } catch (final ExecutionException ex) { Assert.assertTrue(ex.getCause() instanceof ConnectException); } totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); } @Test public void testConnectUnknownHost() throws Exception { final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest.getException()).thenReturn(new IOException()); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); @SuppressWarnings("unchecked") final SocketAddressResolver addressResolver = Mockito.mock(SocketAddressResolver.class); Mockito.when(addressResolver.resolveRemoteAddress("somehost")).thenThrow(new UnknownHostException()); final LocalSessionPool pool = new LocalSessionPool(ioreactor, addressResolver, 2, 10); final Future future = pool.lease("somehost", null); Assert.assertTrue(future.isDone()); Assert.assertFalse(future.isCancelled()); try { future.get(); Assert.fail("ExecutionException should have been thrown"); } catch (final ExecutionException ex) { Assert.assertTrue(ex.getCause() instanceof UnknownHostException); } } @Test public void testLeaseRelease() throws Exception { final IOSession iosession1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest1.getSession()).thenReturn(iosession1); final IOSession iosession2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getAttachment()).thenReturn("otherhost"); Mockito.when(sessionRequest2.getSession()).thenReturn(iosession2); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest1); Mockito.when(ioreactor.connect( Mockito.eq(InetSocketAddress.createUnresolved("otherhost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest2); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); final Future future1 = pool.lease("somehost", null); pool.requestCompleted(sessionRequest1); final Future future2 = pool.lease("somehost", null); pool.requestCompleted(sessionRequest1); final Future future3 = pool.lease("otherhost", null); pool.requestCompleted(sessionRequest2); final LocalPoolEntry entry1 = future1.get(); Assert.assertNotNull(entry1); final LocalPoolEntry entry2 = future2.get(); Assert.assertNotNull(entry2); final LocalPoolEntry entry3 = future3.get(); Assert.assertNotNull(entry3); pool.release(entry1, true); pool.release(entry2, true); pool.release(entry3, false); Mockito.verify(iosession1, Mockito.never()).close(); Mockito.verify(iosession2, Mockito.times(1)).close(); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(2, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); } @Test public void testLeaseIllegal() throws Exception { final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); try { pool.lease(null, null, 0, TimeUnit.MILLISECONDS, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } try { pool.lease("somehost", null, 0, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException expected) { } } @Test public void testReleaseUnknownEntry() throws Exception { final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 2); pool.release(new LocalPoolEntry("somehost", Mockito.mock(IOSession.class)), true); } @Test public void testMaxLimits() throws Exception { final IOSession iosession1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest1.getSession()).thenReturn(iosession1); final IOSession iosession2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getAttachment()).thenReturn("otherhost"); Mockito.when(sessionRequest2.getSession()).thenReturn(iosession2); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest1); Mockito.when(ioreactor.connect( Mockito.eq(InetSocketAddress.createUnresolved("otherhost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest2); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); pool.setMaxPerRoute("somehost", 2); pool.setMaxPerRoute("otherhost", 1); pool.setMaxTotal(3); final Future future1 = pool.lease("somehost", null); pool.requestCompleted(sessionRequest1); final Future future2 = pool.lease("somehost", null); pool.requestCompleted(sessionRequest1); final Future future3 = pool.lease("otherhost", null); pool.requestCompleted(sessionRequest2); final LocalPoolEntry entry1 = future1.get(); Assert.assertNotNull(entry1); final LocalPoolEntry entry2 = future2.get(); Assert.assertNotNull(entry2); final LocalPoolEntry entry3 = future3.get(); 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()); Assert.assertEquals(0, totals.getPending()); final Future future4 = pool.lease("somehost", null); final Future future5 = pool.lease("somehost", null); final Future future6 = pool.lease("otherhost", null); final Future future7 = pool.lease("somehost", null); final Future future8 = pool.lease("somehost", null); final Future future9 = pool.lease("otherhost", null); Assert.assertTrue(future4.isDone()); final LocalPoolEntry entry4 = future4.get(); Assert.assertNotNull(entry4); Assert.assertTrue(future5.isDone()); final LocalPoolEntry entry5 = future5.get(); Assert.assertNotNull(entry5); Assert.assertTrue(future6.isDone()); final LocalPoolEntry entry6 = future6.get(); Assert.assertNotNull(entry6); Assert.assertFalse(future7.isDone()); Assert.assertFalse(future8.isDone()); Assert.assertFalse(future9.isDone()); Mockito.verify(ioreactor, Mockito.times(3)).connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); pool.release(entry4, true); pool.release(entry5, false); pool.release(entry6, true); Assert.assertTrue(future7.isDone()); Assert.assertFalse(future8.isDone()); Assert.assertTrue(future9.isDone()); Mockito.verify(ioreactor, Mockito.times(4)).connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); } @Test public void testConnectionRedistributionOnTotalMaxLimit() throws Exception { final IOSession iosession1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest1.getSession()).thenReturn(iosession1); final IOSession iosession2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest2.getSession()).thenReturn(iosession2); final IOSession iosession3 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest3 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest3.getAttachment()).thenReturn("otherhost"); Mockito.when(sessionRequest3.getSession()).thenReturn(iosession3); final IOSession iosession4 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest4 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest4.getAttachment()).thenReturn("otherhost"); Mockito.when(sessionRequest4.getSession()).thenReturn(iosession4); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest1, sessionRequest2, sessionRequest1); Mockito.when(ioreactor.connect( Mockito.eq(InetSocketAddress.createUnresolved("otherhost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest3, sessionRequest4, sessionRequest3); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); pool.setMaxPerRoute("somehost", 2); pool.setMaxPerRoute("otherhost", 2); pool.setMaxTotal(2); final Future future1 = pool.lease("somehost", null); final Future future2 = pool.lease("somehost", null); final Future future3 = pool.lease("otherhost", null); final Future future4 = pool.lease("otherhost", null); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); Mockito.verify(ioreactor, Mockito.never()).connect( Mockito.eq(InetSocketAddress.createUnresolved("otherhost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); pool.requestCompleted(sessionRequest1); pool.requestCompleted(sessionRequest2); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = future1.get(); Assert.assertNotNull(entry1); Assert.assertTrue(future2.isDone()); final LocalPoolEntry entry2 = future2.get(); Assert.assertNotNull(entry2); Assert.assertFalse(future3.isDone()); Assert.assertFalse(future4.isDone()); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(2, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); pool.release(entry1, true); pool.release(entry2, true); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("otherhost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); pool.requestCompleted(sessionRequest3); pool.requestCompleted(sessionRequest4); Assert.assertTrue(future3.isDone()); final LocalPoolEntry entry3 = future3.get(); Assert.assertNotNull(entry3); Assert.assertTrue(future4.isDone()); final LocalPoolEntry entry4 = future4.get(); Assert.assertNotNull(entry4); totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(2, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); final Future future5 = pool.lease("somehost", null); final Future future6 = pool.lease("otherhost", null); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("otherhost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); pool.release(entry3, true); pool.release(entry4, true); Mockito.verify(ioreactor, Mockito.times(3)).connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("otherhost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); pool.requestCompleted(sessionRequest1); Assert.assertTrue(future5.isDone()); final LocalPoolEntry entry5 = future5.get(); Assert.assertNotNull(entry5); Assert.assertTrue(future6.isDone()); final LocalPoolEntry entry6 = future6.get(); Assert.assertNotNull(entry6); totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(2, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); pool.release(entry5, true); pool.release(entry6, true); Mockito.verify(ioreactor, Mockito.times(3)).connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("otherhost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); totals = pool.getTotalStats(); Assert.assertEquals(2, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); } @Test public void testStatefulConnectionRedistributionOnPerRouteMaxLimit() throws Exception { final IOSession iosession1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest1.getSession()).thenReturn(iosession1); final IOSession iosession2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest2.getSession()).thenReturn(iosession2); final IOSession iosession3 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest3 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest3.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest3.getSession()).thenReturn(iosession3); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest1, sessionRequest2, sessionRequest3); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 10); pool.setMaxPerRoute("somehost", 2); pool.setMaxTotal(2); final Future future1 = pool.lease("somehost", null); final Future future2 = pool.lease("somehost", null); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); pool.requestCompleted(sessionRequest1); pool.requestCompleted(sessionRequest2); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = future1.get(); Assert.assertNotNull(entry1); Assert.assertTrue(future2.isDone()); final LocalPoolEntry entry2 = future2.get(); 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); final Future future3 = pool.lease("somehost", "some-stuff"); final Future future4 = pool.lease("somehost", "some-stuff"); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry3 = future3.get(); Assert.assertNotNull(entry3); Assert.assertTrue(future4.isDone()); final LocalPoolEntry entry4 = future4.get(); Assert.assertNotNull(entry4); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); pool.release(entry3, true); pool.release(entry4, true); totals = pool.getTotalStats(); Assert.assertEquals(2, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); final Future future5 = pool.lease("somehost", "some-other-stuff"); Assert.assertFalse(future5.isDone()); Mockito.verify(ioreactor, Mockito.times(3)).connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); Mockito.verify(iosession2).close(); Mockito.verify(iosession1, Mockito.never()).close(); totals = pool.getTotalStats(); Assert.assertEquals(1, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(1, totals.getPending()); } @Test public void testCreateNewIfExpired() throws Exception { final IOSession iosession1 = Mockito.mock(IOSession.class); Mockito.when(iosession1.isClosed()).thenReturn(Boolean.TRUE); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest1.getSession()).thenReturn(iosession1); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.eq(InetSocketAddress.createUnresolved("somehost", 80)), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest1); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 2); final Future future1 = pool.lease("somehost", null); Mockito.verify(ioreactor, Mockito.times(1)).connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); pool.requestCompleted(sessionRequest1); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = future1.get(); Assert.assertNotNull(entry1); entry1.updateExpiry(1, TimeUnit.MILLISECONDS); pool.release(entry1, true); Thread.sleep(200L); final Future future2 = pool.lease("somehost", null); Assert.assertFalse(future2.isDone()); Mockito.verify(iosession1).close(); Mockito.verify(ioreactor, Mockito.times(2)).connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class)); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(1, totals.getPending()); Assert.assertEquals(Collections.singleton("somehost"), pool.getRoutes()); final PoolStats stats = pool.getStats("somehost"); Assert.assertEquals(0, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); Assert.assertEquals(1, stats.getPending()); } @Test public void testCloseExpired() throws Exception { final IOSession iosession1 = Mockito.mock(IOSession.class); Mockito.when(iosession1.isClosed()).thenReturn(Boolean.TRUE); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest1.getSession()).thenReturn(iosession1); final IOSession iosession2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest2.getSession()).thenReturn(iosession2); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest1, sessionRequest2); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 2); final Future future1 = pool.lease("somehost", null); final Future future2 = pool.lease("somehost", null); pool.requestCompleted(sessionRequest1); pool.requestCompleted(sessionRequest2); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = future1.get(); Assert.assertNotNull(entry1); Assert.assertTrue(future2.isDone()); final LocalPoolEntry entry2 = future2.get(); 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(iosession1).close(); Mockito.verify(iosession2, Mockito.never()).close(); final PoolStats totals = pool.getTotalStats(); Assert.assertEquals(1, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); final PoolStats stats = pool.getStats("somehost"); Assert.assertEquals(1, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); Assert.assertEquals(0, stats.getPending()); } @Test public void testCloseIdle() throws Exception { final IOSession iosession1 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest1.getSession()).thenReturn(iosession1); final IOSession iosession2 = Mockito.mock(IOSession.class); final SessionRequest sessionRequest2 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest2.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest2.getSession()).thenReturn(iosession2); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest1, sessionRequest2); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 2); final Future future1 = pool.lease("somehost", null); final Future future2 = pool.lease("somehost", null); pool.requestCompleted(sessionRequest1); pool.requestCompleted(sessionRequest2); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = future1.get(); Assert.assertNotNull(entry1); Assert.assertTrue(future2.isDone()); final LocalPoolEntry entry2 = future2.get(); 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(iosession1).close(); Mockito.verify(iosession2, Mockito.never()).close(); PoolStats totals = pool.getTotalStats(); Assert.assertEquals(1, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); PoolStats stats = pool.getStats("somehost"); Assert.assertEquals(1, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); Assert.assertEquals(0, stats.getPending()); pool.closeIdle(-1, TimeUnit.MILLISECONDS); Mockito.verify(iosession2).close(); totals = pool.getTotalStats(); Assert.assertEquals(0, totals.getAvailable()); Assert.assertEquals(0, totals.getLeased()); Assert.assertEquals(0, totals.getPending()); stats = pool.getStats("somehost"); Assert.assertEquals(0, stats.getAvailable()); Assert.assertEquals(0, stats.getLeased()); Assert.assertEquals(0, stats.getPending()); } @Test public void testLeaseRequestTimeout() throws Exception { final IOSession iosession1 = Mockito.mock(IOSession.class); Mockito.when(iosession1.isClosed()).thenReturn(Boolean.TRUE); final SessionRequest sessionRequest1 = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest1.getAttachment()).thenReturn("somehost"); Mockito.when(sessionRequest1.getSession()).thenReturn(iosession1); final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); Mockito.when(ioreactor.connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.any(), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest1); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 1, 1); final Future future1 = pool.lease("somehost", null, 0, TimeUnit.MILLISECONDS, null); final Future future2 = pool.lease("somehost", null, 0, TimeUnit.MILLISECONDS, null); final Future future3 = pool.lease("somehost", null, 10, TimeUnit.MILLISECONDS, null); pool.requestCompleted(sessionRequest1); Assert.assertTrue(future1.isDone()); final LocalPoolEntry entry1 = future1.get(); Assert.assertNotNull(entry1); Assert.assertFalse(future2.isDone()); Assert.assertFalse(future3.isDone()); Thread.sleep(100); pool.validatePendingRequests(); Assert.assertFalse(future2.isDone()); Assert.assertTrue(future3.isDone()); } @Test(expected=IllegalArgumentException.class) public void testCloseIdleInvalid() throws Exception { final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 2); pool.closeIdle(50, null); } @Test(expected=IllegalArgumentException.class) public void testGetStatsInvalid() throws Exception { final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 2); pool.getStats(null); } @Test public void testSetMaxInvalid() throws Exception { final ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 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 ConnectingIOReactor ioreactor = Mockito.mock(ConnectingIOReactor.class); final LocalSessionPool pool = new LocalSessionPool(ioreactor, 2, 2); pool.shutdown(1000); Mockito.verify(ioreactor, Mockito.times(1)).shutdown(1000); pool.shutdown(1000); Mockito.verify(ioreactor, Mockito.times(1)).shutdown(1000); 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(IOSession.class)), true); pool.requestCompleted(Mockito.mock(SessionRequest.class)); pool.requestFailed(Mockito.mock(SessionRequest.class)); pool.requestCancelled(Mockito.mock(SessionRequest.class)); pool.requestTimeout(Mockito.mock(SessionRequest.class)); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/util/0040755 0000000 0000000 00000000000 12613456024 026126 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/util/ContentDecoderMock.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/util/ContentDecoderMock.jav0100644 0000000 0000000 00000003746 12613456024 032351 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import org.apache.http.nio.ContentDecoder; public class ContentDecoderMock implements ContentDecoder { private final ReadableByteChannel channel; private boolean completed; public ContentDecoderMock(final ReadableByteChannel channel) { super(); this.channel = channel; } @Override public int read(final ByteBuffer dst) throws IOException { if (this.completed) { return -1; } final int bytesRead = this.channel.read(dst); if (bytesRead == -1) { this.completed = true; } return bytesRead; } @Override public boolean isCompleted() { return this.completed; } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/util/TestBuffers.java0100644 0000000 0000000 00000016112 12613456024 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 * . * */ package org.apache.http.nio.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import org.apache.http.Consts; import org.apache.http.ReadableByteChannelMock; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.reactor.SessionOutputBufferImpl; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.util.EncodingUtils; import org.junit.Assert; import org.junit.Test; /** * Buffer tests. */ public class TestBuffers { @Test public void testInputBufferOperations() throws IOException { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final ContentDecoder decoder = new ContentDecoderMock(channel); final SimpleInputBuffer buffer = new SimpleInputBuffer(4, DirectByteBufferAllocator.INSTANCE); final int count = buffer.consumeContent(decoder); Assert.assertEquals(16, count); Assert.assertTrue(decoder.isCompleted()); final byte[] b1 = new byte[5]; int len = buffer.read(b1); Assert.assertEquals("stuff", EncodingUtils.getAsciiString(b1, 0, len)); final int c = buffer.read(); Assert.assertEquals(';', c); final byte[] b2 = new byte[1024]; len = buffer.read(b2); Assert.assertEquals("more stuff", EncodingUtils.getAsciiString(b2, 0, len)); Assert.assertEquals(-1, buffer.read()); Assert.assertEquals(-1, buffer.read(b2)); Assert.assertEquals(-1, buffer.read(b2, 0, b2.length)); Assert.assertTrue(buffer.isEndOfStream()); buffer.reset(); Assert.assertFalse(buffer.isEndOfStream()); } @Test public void testOutputBufferOperations() throws IOException { final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel channel = Channels.newChannel(outstream); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ContentEncoder encoder = new ContentEncoderMock(channel, outbuf, metrics); final SimpleOutputBuffer buffer = new SimpleOutputBuffer(4, DirectByteBufferAllocator.INSTANCE); buffer.write(EncodingUtils.getAsciiBytes("stuff")); buffer.write(';'); buffer.produceContent(encoder); buffer.write(EncodingUtils.getAsciiBytes("more ")); buffer.write(EncodingUtils.getAsciiBytes("stuff")); buffer.produceContent(encoder); final byte[] content = outstream.toByteArray(); Assert.assertEquals("stuff;more stuff", EncodingUtils.getAsciiString(content)); } @Test public void testBufferInfo() throws Exception { final SimpleOutputBuffer buffer = new SimpleOutputBuffer(8, DirectByteBufferAllocator.INSTANCE); Assert.assertEquals(0, buffer.length()); Assert.assertEquals(8, buffer.available()); buffer.write(new byte[] {'1', '2', '3', '4'}); Assert.assertEquals(4, buffer.length()); Assert.assertEquals(4, buffer.available()); buffer.write(new byte[] {'1', '2', '3', '4', '5', '6', '7', '8'}); Assert.assertEquals(12, buffer.length()); Assert.assertEquals(0, buffer.available()); } @Test public void testInputBufferNullInput() throws IOException { final SimpleInputBuffer buffer = new SimpleInputBuffer(4, DirectByteBufferAllocator.INSTANCE); Assert.assertEquals(0, buffer.read(null)); Assert.assertEquals(0, buffer.read(null, 0, 0)); } @Test public void testOutputBufferNullInput() throws IOException { final SimpleOutputBuffer buffer = new SimpleOutputBuffer(4, DirectByteBufferAllocator.INSTANCE); buffer.write(null); buffer.write(null, 0, 10); Assert.assertFalse(buffer.hasData()); } @Test public void testDirectByteBufferAllocator() { final DirectByteBufferAllocator allocator = new DirectByteBufferAllocator(); ByteBuffer buffer = allocator.allocate(1); Assert.assertNotNull(buffer); Assert.assertTrue(buffer.isDirect()); Assert.assertEquals(0, buffer.position()); Assert.assertEquals(1, buffer.limit()); Assert.assertEquals(1, buffer.capacity()); buffer = allocator.allocate(2048); Assert.assertTrue(buffer.isDirect()); Assert.assertEquals(0, buffer.position()); Assert.assertEquals(2048, buffer.limit()); Assert.assertEquals(2048, buffer.capacity()); buffer = allocator.allocate(0); Assert.assertTrue(buffer.isDirect()); Assert.assertEquals(0, buffer.position()); Assert.assertEquals(0, buffer.limit()); Assert.assertEquals(0, buffer.capacity()); } @Test public void testHeapByteBufferAllocator() { final HeapByteBufferAllocator allocator = new HeapByteBufferAllocator(); ByteBuffer buffer = allocator.allocate(1); Assert.assertNotNull(buffer); Assert.assertFalse(buffer.isDirect()); Assert.assertEquals(0, buffer.position()); Assert.assertEquals(1, buffer.limit()); Assert.assertEquals(1, buffer.capacity()); buffer = allocator.allocate(2048); Assert.assertFalse(buffer.isDirect()); Assert.assertEquals(0, buffer.position()); Assert.assertEquals(2048, buffer.limit()); Assert.assertEquals(2048, buffer.capacity()); buffer = allocator.allocate(0); Assert.assertFalse(buffer.isDirect()); Assert.assertEquals(0, buffer.position()); Assert.assertEquals(0, buffer.limit()); Assert.assertEquals(0, buffer.capacity()); } } ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/util/ContentEncoderMock.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/util/ContentEncoderMock.jav0100644 0000000 0000000 00000004054 12613456024 032354 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.codecs.AbstractContentEncoder; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.util.Asserts; public class ContentEncoderMock extends AbstractContentEncoder { public ContentEncoderMock( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { super(channel, buffer, metrics); } @Override public int write(final ByteBuffer src) throws IOException { if (src == null) { return 0; } Asserts.check(!isCompleted(), "Decoding process already completed"); return this.channel.write(src); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/0040755 0000000 0000000 00000000000 12613456023 027473 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000163 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestServerSidePipelining.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestServerSideP0100644 0000000 0000000 00000035273 12613456023 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.nio.integration; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; 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.entity.ContentType; import org.apache.http.nio.entity.NByteArrayEntity; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.BasicAsyncRequestHandler; import org.apache.http.nio.protocol.UriHttpAsyncRequestHandlerMapper; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.testserver.HttpCoreNIOTestBase; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseServer; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests for handling pipelined requests. */ public class TestServerSidePipelining extends HttpCoreNIOTestBase { @Before public void setUp() throws Exception { initServer(); this.server.setHttpProcessor(new ImmutableHttpProcessor( new ResponseServer("TEST-SERVER/1.1"), new ResponseContent(), new ResponseConnControl())); final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(); this.server.registerHandler("*", new BasicAsyncRequestHandler(new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final String content = "thank you very much"; final NStringEntity entity = new NStringEntity(content, ContentType.DEFAULT_TEXT); response.setEntity(entity); } })); this.server.registerHandler("/goodbye", new BasicAsyncRequestHandler(new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final String content = "and goodbye"; final NStringEntity entity = new NStringEntity(content, ContentType.DEFAULT_TEXT); response.setEntity(entity); response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); } })); this.server.registerHandler("/echo", new BasicAsyncRequestHandler(new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final HttpEntity responseEntity; if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity requestEntity = ((HttpEntityEnclosingRequest) request).getEntity(); final ContentType contentType = ContentType.getOrDefault(requestEntity); responseEntity = new NByteArrayEntity( EntityUtils.toByteArray(requestEntity), contentType); } else { responseEntity = new NStringEntity("Say what?", ContentType.DEFAULT_TEXT); } response.setEntity(responseEntity); } })); } @After public void tearDown() throws Exception { shutDownServer(); } @Test public void testGetRequestPipelining() throws Exception { this.server.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); final Socket socket = new Socket("localhost", address.getPort()); try { final OutputStream outstream = socket.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outstream, "US-ASCII")); writer.write("GET / HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("\r\n"); writer.write("GET / HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("\r\n"); writer.write("GET / HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("\r\n"); writer.write("GET / HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("Connection: close\r\n"); writer.write("\r\n"); writer.flush(); final InputStream instream = socket.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "US-ASCII")); final StringBuilder buf = new StringBuilder(); final char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buf.append(tmp, 0, l); } reader.close(); writer.close(); final String expected = "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 19\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "thank you very much" + "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 19\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "thank you very much" + "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 19\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "thank you very much" + "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 19\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "Connection: close\r\n" + "\r\n" + "thank you very much"; Assert.assertEquals(expected, buf.toString()); } finally { socket.close(); } } @Test public void testPostRequestPipelining() throws Exception { this.server.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); final Socket socket = new Socket("localhost", address.getPort()); try { final OutputStream outstream = socket.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outstream, "US-ASCII")); writer.write("POST /echo HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("Content-Length: 16\r\n"); writer.write("Content-Type: text/plain; charset=ISO-8859-1\r\n"); writer.write("\r\n"); writer.write("blah blah blah\r\n"); writer.write("POST /echo HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("Transfer-Encoding: chunked\r\n"); writer.write("Content-Type: text/plain; charset=ISO-8859-1\r\n"); writer.write("\r\n"); writer.write("10\r\n"); writer.write("yada yada yada\r\n"); writer.write("\r\n"); writer.write("0\r\n"); writer.write("\r\n"); writer.write("GET / HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("\r\n"); writer.write("GET /goodbye HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("\r\n"); writer.flush(); final InputStream instream = socket.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "US-ASCII")); final StringBuilder buf = new StringBuilder(); final char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buf.append(tmp, 0, l); } reader.close(); writer.close(); final String expected = "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 16\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "blah blah blah\r\n" + "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 16\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "yada yada yada\r\n" + "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 19\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "thank you very much" + "HTTP/1.1 200 OK\r\n" + "Connection: Close\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 11\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "and goodbye"; Assert.assertEquals(expected, buf.toString()); } finally { socket.close(); } } @Test public void testPostRequestPipeliningExpectContinue() throws Exception { this.server.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); final Socket socket = new Socket("localhost", address.getPort()); try { final OutputStream outstream = socket.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outstream, "US-ASCII")); writer.write("POST /echo HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("Expect: 100-Continue\r\n"); writer.write("Content-Length: 16\r\n"); writer.write("Content-Type: text/plain; charset=ISO-8859-1\r\n"); writer.write("\r\n"); writer.write("blah blah blah\r\n"); writer.write("POST /echo HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("Expect: 100-Continue\r\n"); writer.write("Content-Length: 16\r\n"); writer.write("Content-Type: text/plain; charset=ISO-8859-1\r\n"); writer.write("\r\n"); writer.write("yada yada yada\r\n"); writer.write("POST /echo HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("Expect: 100-Continue\r\n"); writer.write("Content-Length: 16\r\n"); writer.write("Content-Type: text/plain; charset=ISO-8859-1\r\n"); writer.write("Connection: close\r\n"); writer.write("\r\n"); writer.write("booo booo booo\r\n"); writer.flush(); final InputStream instream = socket.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "US-ASCII")); final StringBuilder buf = new StringBuilder(); final char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buf.append(tmp, 0, l); } reader.close(); writer.close(); final String expected = "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 16\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "blah blah blah\r\n" + "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 16\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "\r\n" + "yada yada yada\r\n" + "HTTP/1.1 200 OK\r\n" + "Server: TEST-SERVER/1.1\r\n" + "Content-Length: 16\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "Connection: close\r\n" + "\r\n" + "booo booo booo\r\n"; Assert.assertEquals(expected, buf.toString()); } finally { socket.close(); } } } ././@LongLink0100644 0000000 0000000 00000000172 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncHandlerCancellable.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncHa0100644 0000000 0000000 00000016525 12613456023 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.nio.integration; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.concurrent.Cancellable; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.protocol.BasicAsyncRequestConsumer; import org.apache.http.nio.protocol.HttpAsyncExchange; import org.apache.http.nio.protocol.HttpAsyncRequestConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestHandler; import org.apache.http.nio.protocol.HttpAsyncResponseProducer; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.testserver.HttpCoreNIOTestBase; import org.apache.http.protocol.HttpContext; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestHttpAsyncHandlerCancellable extends HttpCoreNIOTestBase { @Before public void setUp() throws Exception { initServer(); } @After public void tearDown() throws Exception { shutDownServer(); } @Test public void testResponsePrematureTermination() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final HttpAsyncResponseProducer responseProducer = new HttpAsyncResponseProducer() { @Override public HttpResponse generateResponse() { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentType(ContentType.DEFAULT_BINARY.toString()); entity.setChunked(true); response.setEntity(entity); return response; } @Override public void close() throws IOException { latch.countDown(); } @Override public void responseCompleted(final HttpContext context) { } @Override public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { // suspend output ioctrl.suspendOutput(); } @Override public void failed(final Exception ex) { } }; this.server.registerHandler("*", new HttpAsyncRequestHandler() { @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) throws HttpException, IOException { return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest data, final HttpAsyncExchange httpExchange, final HttpContext context) throws HttpException, IOException { httpExchange.submitResponse(responseProducer); } }); this.server.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); final Socket socket = new Socket("localhost", address.getPort()); try { final OutputStream outstream = socket.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outstream, "US-ASCII")); writer.write("GET /long HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("\r\n"); writer.flush(); Thread.sleep(250); writer.close(); } finally { socket.close(); } Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test public void testRequestCancelled() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final Cancellable cancellable = new Cancellable() { @Override public boolean cancel() { latch.countDown(); return true; } }; this.server.registerHandler("*", new HttpAsyncRequestHandler() { @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) throws HttpException, IOException { return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest data, final HttpAsyncExchange httpExchange, final HttpContext context) throws HttpException, IOException { httpExchange.setCallback(cancellable); // do not submit a response; } }); this.server.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); final Socket socket = new Socket("localhost", address.getPort()); try { final OutputStream outstream = socket.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outstream, "US-ASCII")); writer.write("GET /long HTTP/1.1\r\n"); writer.write("Host: localhost\r\n"); writer.write("\r\n"); writer.flush(); Thread.sleep(250); writer.close(); } finally { socket.close(); } Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); } } ././@LongLink0100644 0000000 0000000 00000000174 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncPrematureTermination.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncPr0100644 0000000 0000000 00000023426 12613456023 032501 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.integration; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.http.Consts; import org.apache.http.HttpConnection; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.concurrent.FutureCallback; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.BasicAsyncRequestConsumer; import org.apache.http.nio.protocol.BasicAsyncResponseProducer; import org.apache.http.nio.protocol.HttpAsyncExchange; import org.apache.http.nio.protocol.HttpAsyncRequestConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestHandler; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.testserver.HttpCoreNIOTestBase; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestHttpAsyncPrematureTermination extends HttpCoreNIOTestBase { @Before public void setUp() throws Exception { initServer(); initClient(); } @After public void tearDown() throws Exception { shutDownClient(); shutDownServer(); } private InetSocketAddress start() throws Exception { this.server.start(); this.client.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); return (InetSocketAddress) endpoint.getAddress(); } @Test public void testConnectionTerminatedProcessingRequest() throws Exception { this.server.registerHandler("*", new HttpAsyncRequestHandler() { @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) throws HttpException, IOException { final HttpConnection conn = (HttpConnection) context.getAttribute( HttpCoreContext.HTTP_CONNECTION); conn.shutdown(); return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest request, final HttpAsyncExchange httpExchange, final HttpContext context) throws HttpException, IOException { final HttpResponse response = httpExchange.getResponse(); response.setEntity(new NStringEntity("all is well", ContentType.TEXT_PLAIN)); httpExchange.submitResponse(); } }); final InetSocketAddress address = start(); final HttpHost target = new HttpHost("localhost", address.getPort()); final CountDownLatch latch = new CountDownLatch(1); final FutureCallback callback = new FutureCallback() { @Override public void cancelled() { latch.countDown(); } @Override public void failed(final Exception ex) { latch.countDown(); } @Override public void completed(final HttpResponse response) { Assert.fail(); } }; final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); this.client.execute(target, request, context, callback); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test public void testConnectionTerminatedHandlingRequest() throws Exception { final CountDownLatch responseStreamClosed = new CountDownLatch(1); final InputStream testInputStream = new ByteArrayInputStream( "all is well".getBytes(Consts.ASCII)) { @Override public void close() throws IOException { responseStreamClosed.countDown(); super.close(); } }; this.server.registerHandler("*", new HttpAsyncRequestHandler() { @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) throws HttpException, IOException { return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest request, final HttpAsyncExchange httpExchange, final HttpContext context) throws HttpException, IOException { final HttpConnection conn = (HttpConnection) context.getAttribute( HttpCoreContext.HTTP_CONNECTION); conn.shutdown(); final HttpResponse response = httpExchange.getResponse(); response.setEntity(new InputStreamEntity(testInputStream, -1)); httpExchange.submitResponse(); } }); final InetSocketAddress address = start(); final HttpHost target = new HttpHost("localhost", address.getPort()); final CountDownLatch latch = new CountDownLatch(1); final FutureCallback callback = new FutureCallback() { @Override public void cancelled() { latch.countDown(); } @Override public void failed(final Exception ex) { latch.countDown(); } @Override public void completed(final HttpResponse response) { Assert.fail(); } }; final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); this.client.execute(target, request, context, callback); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); Assert.assertTrue(responseStreamClosed.await(5, TimeUnit.SECONDS)); } @Test public void testConnectionTerminatedSendingResponse() throws Exception { this.server.registerHandler("*", new HttpAsyncRequestHandler() { @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) throws HttpException, IOException { return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest request, final HttpAsyncExchange httpExchange, final HttpContext context) throws HttpException, IOException { final HttpResponse response = httpExchange.getResponse(); response.setEntity(new NStringEntity("all is well", ContentType.TEXT_PLAIN)); httpExchange.submitResponse(new BasicAsyncResponseProducer(response) { @Override public synchronized void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { ioctrl.shutdown(); } }); } }); final InetSocketAddress address = start(); final HttpHost target = new HttpHost("localhost", address.getPort()); final CountDownLatch latch = new CountDownLatch(1); final FutureCallback callback = new FutureCallback() { @Override public void cancelled() { latch.countDown(); } @Override public void failed(final Exception ex) { latch.countDown(); } @Override public void completed(final HttpResponse response) { Assert.fail(); } }; final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); this.client.execute(target, request, context, callback); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); } } ././@LongLink0100644 0000000 0000000 00000000157 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncTimeout.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncTi0100644 0000000 0000000 00000010754 12613456023 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.nio.integration; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.concurrent.FutureCallback; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.protocol.BasicAsyncRequestProducer; import org.apache.http.nio.protocol.BasicAsyncResponseConsumer; import org.apache.http.nio.testserver.HttpCoreNIOTestBase; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class TestHttpAsyncTimeout extends HttpCoreNIOTestBase { @Parameterized.Parameters(name = "{0}") public static Collection protocols() { return Arrays.asList(new Object[][]{ {ProtocolScheme.http}, {ProtocolScheme.https}, }); } public TestHttpAsyncTimeout(final ProtocolScheme scheme) { super(scheme); } private ServerSocket serverSocket; @Before public void setUp() throws Exception { initClient(); } @After public void tearDown() throws Exception { serverSocket.close(); shutDownClient(); } private InetSocketAddress start() throws Exception { this.client.start(); serverSocket = new ServerSocket(0); return new InetSocketAddress(serverSocket.getInetAddress(), serverSocket.getLocalPort()); } @Test public void testHandshakeTimeout() throws Exception { // This test creates a server socket and accepts the incoming // socket connection without reading any data. The client should // connect, be unable to progress through the handshake, and then // time out when SO_TIMEOUT has elapsed. final InetSocketAddress address = start(); final HttpHost target = new HttpHost("localhost", address.getPort(), getScheme().name()); final CountDownLatch latch = new CountDownLatch(1); final FutureCallback callback = new FutureCallback() { @Override public void cancelled() { latch.countDown(); } @Override public void failed(final Exception ex) { latch.countDown(); } @Override public void completed(final HttpResponse response) { Assert.fail(); } }; final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); this.client.setTimeout(1000); this.client.execute( new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), context, callback); final Socket accepted = serverSocket.accept(); try { Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { accepted.close(); } } } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestCustomSSL.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestCustomSSL.j0100644 0000000 0000000 00000013423 12613456023 032342 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.integration; import java.io.IOException; import java.math.BigInteger; import java.net.InetSocketAddress; import java.net.URL; import java.util.concurrent.Future; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.impl.nio.pool.BasicNIOConnFactory; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.protocol.BasicAsyncRequestHandler; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; import org.apache.http.nio.testserver.ClientConnectionFactory; import org.apache.http.nio.testserver.HttpClientNio; import org.apache.http.nio.testserver.HttpServerNio; import org.apache.http.nio.testserver.ServerConnectionFactory; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.ssl.SSLContextBuilder; import org.junit.After; import org.junit.Assert; import org.junit.Test; public class TestCustomSSL { protected HttpServerNio server; protected HttpClientNio client; @After public void shutDownClient() throws Exception { if (this.client != null) { this.client.shutdown(); this.client = null; } } @After public void shutDownServer() throws Exception { if (this.server != null) { this.server.shutdown(); this.server = null; } } @Test public void testCustomSSLContext() throws Exception { final SSLSetupHandler sslSetupHandler = new SSLSetupHandler() { @Override public void initalize( final SSLEngine sslengine) throws SSLException { } @Override public void verify( final IOSession iosession, final SSLSession sslsession) throws SSLException { final BigInteger sslid = new BigInteger(sslsession.getId()); iosession.setAttribute("ssl-id", sslid); } }; final HttpRequestHandler requestHandler = new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final NHttpConnection conn = (NHttpConnection) context.getAttribute( HttpCoreContext.HTTP_CONNECTION); final BigInteger sslid = (BigInteger) conn.getContext().getAttribute( "ssl-id"); Assert.assertNotNull(sslid); } }; final URL keyStoreURL = getClass().getResource("/test.keystore"); final String storePassword = "nopassword"; final SSLContext serverSSLContext = SSLContextBuilder.create() .loadTrustMaterial(keyStoreURL, storePassword.toCharArray()) .loadKeyMaterial(keyStoreURL, storePassword.toCharArray(), storePassword.toCharArray()) .build(); this.server = new HttpServerNio(); this.server.setConnectionFactory(new ServerConnectionFactory(serverSSLContext, sslSetupHandler)); this.server.setTimeout(5000); final SSLContext clientSSLContext = SSLContextBuilder.create() .loadTrustMaterial(keyStoreURL, storePassword.toCharArray()) .build(); this.client = new HttpClientNio(new BasicNIOConnFactory(new ClientConnectionFactory(clientSSLContext), null)); this.client.setTimeout(5000); this.server.registerHandler("*", new BasicAsyncRequestHandler(requestHandler)); this.server.start(); this.client.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); final HttpHost target = new HttpHost("localhost", address.getPort()); final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final Future future = this.client.execute(target, request); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); } } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestTruncatedChunks.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestTruncatedCh0100644 0000000 0000000 00000023367 12613456023 032472 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.integration; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.MalformedChunkCodingException; import org.apache.http.TruncatedChunkException; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.DefaultNHttpServerConnection; import org.apache.http.impl.nio.codecs.AbstractContentEncoder; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.ContentInputStream; import org.apache.http.nio.protocol.AbstractAsyncResponseConsumer; import org.apache.http.nio.protocol.BasicAsyncRequestHandler; import org.apache.http.nio.protocol.BasicAsyncRequestProducer; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.testserver.HttpCoreNIOTestBase; import org.apache.http.nio.testserver.LoggingNHttpServerConnection; import org.apache.http.nio.testserver.ServerConnectionFactory; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.nio.util.SimpleInputBuffer; import org.apache.http.protocol.HttpContext; import org.apache.http.util.CharArrayBuffer; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests for handling truncated chunks. */ public class TestTruncatedChunks extends HttpCoreNIOTestBase { @Before public void setUp() throws Exception { initServer(); initClient(); } @After public void tearDown() throws Exception { shutDownClient(); shutDownServer(); } @Override protected ServerConnectionFactory createServerConnectionFactory() throws Exception { return new CustomServerConnectionFactory(); } private static final byte[] GARBAGE = new byte[] {'1', '2', '3', '4', '5' }; static class BrokenChunkEncoder extends AbstractContentEncoder { private final CharArrayBuffer lineBuffer; private boolean done; public BrokenChunkEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { super(channel, buffer, metrics); this.lineBuffer = new CharArrayBuffer(16); } @Override public void complete() throws IOException { super.complete(); } @Override public int write(final ByteBuffer src) throws IOException { int chunk; if (!this.done) { this.lineBuffer.clear(); this.lineBuffer.append(Integer.toHexString(GARBAGE.length * 10)); this.buffer.writeLine(this.lineBuffer); this.buffer.write(ByteBuffer.wrap(GARBAGE)); this.done = true; chunk = GARBAGE.length; } else { chunk = 0; } final long bytesWritten = this.buffer.flush(this.channel); if (bytesWritten > 0) { this.metrics.incrementBytesTransferred(bytesWritten); } if (!this.buffer.hasData()) { this.channel.close(); } return chunk; } } static class CustomServerConnectionFactory extends ServerConnectionFactory { public CustomServerConnectionFactory() { super(); } @Override public DefaultNHttpServerConnection createConnection(final IOSession session) { return new LoggingNHttpServerConnection(session) { @Override protected ContentEncoder createContentEncoder( final long len, final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { if (len == ContentLengthStrategy.CHUNKED) { return new BrokenChunkEncoder(channel, buffer, metrics); } else { return super.createContentEncoder(len, channel, buffer, metrics); } } }; } } @Test public void testTruncatedChunkException() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler(true))); this.server.start(); this.client.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final HttpHost target = new HttpHost("localhost", ((InetSocketAddress)endpoint.getAddress()).getPort()); final BasicHttpRequest request = new BasicHttpRequest("GET", pattern + "x" + count); final Future future = this.client.execute(target, request); try { future.get(); Assert.fail("ExecutionException should have been thrown"); } catch (final ExecutionException ex) { final Throwable cause = ex.getCause(); Assert.assertTrue(cause instanceof MalformedChunkCodingException); } } static class LenientAsyncResponseConsumer extends AbstractAsyncResponseConsumer { private final SimpleInputBuffer buffer; private volatile HttpResponse response; public LenientAsyncResponseConsumer() { super(); this.buffer = new SimpleInputBuffer(2048, HeapByteBufferAllocator.INSTANCE); } @Override protected void onResponseReceived(final HttpResponse response) { this.response = response; } @Override protected void onEntityEnclosed(final HttpEntity entity, final ContentType contentType) { } @Override protected void onContentReceived( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { boolean finished = false; try { this.buffer.consumeContent(decoder); if (decoder.isCompleted()) { finished = true; } } catch (final TruncatedChunkException ex) { this.buffer.shutdown(); finished = true; } if (finished) { this.response.setEntity( new InputStreamEntity(new ContentInputStream(this.buffer), -1)); } } @Override protected void releaseResources() { } @Override protected HttpResponse buildResult(final HttpContext context) { return this.response; } } @Test public void testIgnoreTruncatedChunkException() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler(true))); this.server.start(); this.client.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final HttpHost target = new HttpHost("localhost", ((InetSocketAddress)endpoint.getAddress()).getPort()); final BasicHttpRequest request = new BasicHttpRequest("GET", pattern + "x" + count); final Future future = this.client.execute( new BasicAsyncRequestProducer(target, request), new LenientAsyncResponseConsumer(), null, null); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(new String(GARBAGE, Consts.ISO_8859_1.name()), EntityUtils.toString(response.getEntity())); } } ././@LongLink0100644 0000000 0000000 00000000157 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/SimpleRequestHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/SimpleRequestHa0100644 0000000 0000000 00000006515 12613456023 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.nio.integration; 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.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.util.EntityUtils; final class SimpleRequestHandler implements HttpRequestHandler { private final boolean chunking; SimpleRequestHandler() { this(false); } SimpleRequestHandler(final boolean chunking) { super(); this.chunking = chunking; } @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final String s = request.getRequestLine().getUri(); final int idx = s.indexOf('x'); if (idx == -1) { throw new HttpException("Unexpected request-URI format"); } final String pattern = s.substring(0, idx); final int count = Integer.parseInt(s.substring(idx + 1, s.length())); response.addHeader("Pattern", pattern); final String content; if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { content = EntityUtils.toString(entity); } else { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); content = "Request entity not available"; } } else { final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < count; i++) { buffer.append(pattern); } content = buffer.toString(); } final NStringEntity entity = new NStringEntity(content, ContentType.DEFAULT_TEXT); entity.setChunked(this.chunking); response.setEntity(entity); } } ././@LongLink0100644 0000000 0000000 00000000162 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/RndTestPatternGenerator.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/RndTestPatternG0100644 0000000 0000000 00000003573 12613456023 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.nio.integration; import java.util.Random; final class RndTestPatternGenerator { private static final Random RND = new Random(); private static final String TEST_CHARS = "0123456789ABCDEF"; public static String generateText() { final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 5; i++) { final char rndchar = TEST_CHARS.charAt(RND.nextInt(TEST_CHARS.length() - 1)); buffer.append(rndchar); } return buffer.toString(); } public static int generateCount(final int max) { return RND.nextInt(max - 1) + 1; } public static boolean generateBoolean() { return RND.nextBoolean(); } } ././@LongLink0100644 0000000 0000000 00000000172 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestClientOutOfSequenceResponse.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestClientOutOf0100644 0000000 0000000 00000007356 12613456023 032461 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.integration; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.apache.http.Consts; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.nio.pool.BasicNIOConnFactory; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.testserver.HttpClientNio; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests for handling out of sequence responses. */ public class TestClientOutOfSequenceResponse { private ServerSocket server; private HttpClientNio client; @Before public void setup() throws Exception { server = new ServerSocket(0, 1); client = new HttpClientNio(new BasicNIOConnFactory(ConnectionConfig.DEFAULT)); } @After public void cleanup() throws Exception { if (client != null) { client.shutdown(); } if (server != null) { server.close(); } } @Test public void testOutOfSequenceResponse() throws Exception { client.setMaxPerRoute(1); client.setMaxTotal(1); client.start(); final HttpHost target = new HttpHost("localhost", server.getLocalPort()); final HttpRequest get1 = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Future future1 = client.execute(target, get1); final HttpRequest get2 = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final Future future2 = client.execute(target, get2); final Socket socket = server.accept(); Thread.sleep(100); for (int i = 0; i < 3; ++i) { socket.getOutputStream().write(( "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "Connection: keep-alive\r\n\r\n").getBytes(Consts.UTF_8)); socket.getOutputStream().flush(); } final HttpResponse response1 = future1.get(); Assert.assertEquals(200, response1.getStatusLine().getStatusCode()); try { final HttpResponse response2 = future2.get(); Assert.assertEquals(200, response2.getStatusLine().getStatusCode()); } catch (ExecutionException ex) { Assert.assertTrue(ex.getCause() instanceof HttpException); } } } ././@LongLink0100644 0000000 0000000 00000000172 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncHandlersPipelining.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncHa0100644 0000000 0000000 00000044334 12613456023 032451 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.integration; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; 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.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.BasicAsyncRequestConsumer; import org.apache.http.nio.protocol.BasicAsyncRequestHandler; import org.apache.http.nio.protocol.BasicAsyncRequestProducer; import org.apache.http.nio.protocol.BasicAsyncResponseConsumer; import org.apache.http.nio.protocol.BasicAsyncResponseProducer; import org.apache.http.nio.protocol.HttpAsyncExchange; import org.apache.http.nio.protocol.HttpAsyncRequestConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestHandler; import org.apache.http.nio.protocol.HttpAsyncRequestProducer; import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.testserver.HttpCoreNIOTestBase; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * HttpCore NIO integration tests for pipelined request processing. */ @RunWith(Parameterized.class) public class TestHttpAsyncHandlersPipelining extends HttpCoreNIOTestBase { @Parameterized.Parameters(name = "{0}") public static Collection protocols() { return Arrays.asList(new Object[][]{ {ProtocolScheme.http}, {ProtocolScheme.https}, }); } public TestHttpAsyncHandlersPipelining(final ProtocolScheme scheme) { super(scheme); } public static final HttpProcessor DEFAULT_HTTP_PROC = new ImmutableHttpProcessor( new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent("TEST-CLIENT/1.1")); @Before public void setUp() throws Exception { initServer(); initClient(); } @After public void tearDown() throws Exception { shutDownClient(); shutDownServer(); } private HttpHost start() throws Exception { this.server.start(); this.client.setHttpProcessor(DEFAULT_HTTP_PROC); this.client.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); return new HttpHost("localhost", address.getPort(), getScheme().name()); } private static String createRequestUri(final String pattern, final int count) { return pattern + "x" + count; } private static String createExpectedString(final String pattern, final int count) { final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < count; i++) { buffer.append(pattern); } return buffer.toString(); } @Test public void testHttpGets() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final String expectedPattern = createExpectedString(pattern, count); final Queue>> queue = new ConcurrentLinkedQueue>>(); for (int i = 0; i < 10; i++) { final String requestUri = createRequestUri(pattern, count); final Future> future = this.client.executePipelined(target, new BasicHttpRequest("GET", requestUri), new BasicHttpRequest("GET", requestUri), new BasicHttpRequest("GET", requestUri)); queue.add(future); } while (!queue.isEmpty()) { final Future> future = queue.remove(); final List responses = future.get(); Assert.assertNotNull(responses); Assert.assertEquals(3, responses.size()); for (HttpResponse response: responses) { Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(expectedPattern, EntityUtils.toString(response.getEntity())); } } } @Test public void testHttpHeads() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final Queue>> queue = new ConcurrentLinkedQueue>>(); for (int i = 0; i < 10; i++) { final String requestUri = createRequestUri(pattern, count); final HttpRequest head1 = new BasicHttpRequest("HEAD", requestUri); final HttpRequest head2 = new BasicHttpRequest("HEAD", requestUri); final BasicHttpEntityEnclosingRequest post1 = new BasicHttpEntityEnclosingRequest("POST", requestUri); post1.setEntity(new NStringEntity("stuff", ContentType.TEXT_PLAIN)); final Future> future = this.client.executePipelined(target, head1, head2, post1); queue.add(future); } while (!queue.isEmpty()) { final Future> future = queue.remove(); final List responses = future.get(); Assert.assertNotNull(responses); Assert.assertEquals(3, responses.size()); for (HttpResponse response: responses) { Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } } } @Test public void testHttpPosts() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final String expectedPattern = createExpectedString(pattern, count); final Queue>> queue = new ConcurrentLinkedQueue>>(); for (int i = 0; i < 10; i++) { final String requestUri = createRequestUri(pattern, count); final HttpEntityEnclosingRequest request1 = new BasicHttpEntityEnclosingRequest("POST", requestUri); final NStringEntity entity1 = new NStringEntity(expectedPattern, ContentType.DEFAULT_TEXT); entity1.setChunked(RndTestPatternGenerator.generateBoolean()); request1.setEntity(entity1); final HttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", requestUri); final NStringEntity entity2 = new NStringEntity(expectedPattern, ContentType.DEFAULT_TEXT); entity2.setChunked(RndTestPatternGenerator.generateBoolean()); request2.setEntity(entity2); final HttpEntityEnclosingRequest request3 = new BasicHttpEntityEnclosingRequest("POST", requestUri); final NStringEntity entity3 = new NStringEntity(expectedPattern, ContentType.DEFAULT_TEXT); entity3.setChunked(RndTestPatternGenerator.generateBoolean()); request3.setEntity(entity3); final Future> future = this.client.executePipelined(target, request1, request2, request3); queue.add(future); } while (!queue.isEmpty()) { final Future> future = queue.remove(); final List responses = future.get(); Assert.assertNotNull(responses); Assert.assertEquals(3, responses.size()); for (HttpResponse response: responses) { Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(expectedPattern, EntityUtils.toString(response.getEntity())); } } } @Test public void testHttpDelayedResponse() throws Exception { class DelayedRequestHandler implements HttpAsyncRequestHandler { private final SimpleRequestHandler requestHandler; public DelayedRequestHandler() { super(); this.requestHandler = new SimpleRequestHandler(); } @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) { return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest request, final HttpAsyncExchange httpexchange, final HttpContext context) throws HttpException, IOException { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); new Thread() { @Override public void run() { // Wait a bit, to make sure this is delayed. try { Thread.sleep(100); } catch(final InterruptedException ie) {} // Set the entity after delaying... try { requestHandler.handle(request, response, context); } catch (final Exception ex) { response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } httpexchange.submitResponse(new BasicAsyncResponseProducer(response)); } }.start(); } } this.server.registerHandler("*", new DelayedRequestHandler()); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern1 = RndTestPatternGenerator.generateText(); final String pattern2 = RndTestPatternGenerator.generateText(); final String pattern3 = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final String expectedPattern1 = createExpectedString(pattern1, count); final String expectedPattern2 = createExpectedString(pattern2, count); final String expectedPattern3 = createExpectedString(pattern3, count); final Queue>> queue = new ConcurrentLinkedQueue>>(); for (int i = 0; i < 1; i++) { final HttpRequest request1 = new BasicHttpRequest("GET", createRequestUri(pattern1, count)); final HttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", createRequestUri(pattern2, count)); final NStringEntity entity2 = new NStringEntity(expectedPattern2, ContentType.DEFAULT_TEXT); entity2.setChunked(RndTestPatternGenerator.generateBoolean()); request2.setEntity(entity2); final HttpEntityEnclosingRequest request3 = new BasicHttpEntityEnclosingRequest("POST", createRequestUri(pattern3, count)); final NStringEntity entity3 = new NStringEntity(expectedPattern3, ContentType.DEFAULT_TEXT); entity3.setChunked(RndTestPatternGenerator.generateBoolean()); request3.setEntity(entity3); final Future> future = this.client.executePipelined(target, request1, request2, request3); queue.add(future); } while (!queue.isEmpty()) { final Future> future = queue.remove(); final List responses = future.get(); Assert.assertNotNull(responses); Assert.assertEquals(3, responses.size()); for (HttpResponse response: responses) { Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } Assert.assertEquals(expectedPattern1, EntityUtils.toString(responses.get(0).getEntity())); Assert.assertEquals(expectedPattern2, EntityUtils.toString(responses.get(1).getEntity())); Assert.assertEquals(expectedPattern3, EntityUtils.toString(responses.get(2).getEntity())); } } @Test public void testUnexpectedConnectionClosure() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new StringEntity("all is well", ContentType.TEXT_PLAIN)); } })); this.server.registerHandler("/boom", new BasicAsyncRequestHandler(new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.setHeader(HttpHeaders.CONNECTION, "Close"); response.setEntity(new StringEntity("boooooom!!!!!", ContentType.TEXT_PLAIN)); } })); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); for (int i = 0; i < 3; i++) { final HttpAsyncRequestProducer p1 = new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/")); final HttpAsyncRequestProducer p2 = new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/")); final HttpAsyncRequestProducer p3 = new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/boom")); final List requestProducers = new ArrayList(); requestProducers.add(p1); requestProducers.add(p2); requestProducers.add(p3); final HttpAsyncResponseConsumer c1 = new BasicAsyncResponseConsumer(); final HttpAsyncResponseConsumer c2 = new BasicAsyncResponseConsumer(); final HttpAsyncResponseConsumer c3 = new BasicAsyncResponseConsumer(); final List> responseConsumers = new ArrayList>(); responseConsumers.add(c1); responseConsumers.add(c2); responseConsumers.add(c3); final Future> future = this.client.executePipelined(target, requestProducers, responseConsumers, null, null); try { future.get(); } catch (ExecutionException ex) { final Throwable cause = ex.getCause(); Assert.assertTrue(cause instanceof ConnectionClosedException); } Assert.assertTrue(c1.isDone()); Assert.assertNotNull(c1.getResult()); Assert.assertTrue(c2.isDone()); Assert.assertNotNull(c2.getResult()); Assert.assertTrue(c2.isDone()); Assert.assertNotNull(c3.getResult()); } } } ././@LongLink0100644 0000000 0000000 00000000160 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncHandlers.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/integration/TestHttpAsyncHa0100644 0000000 0000000 00000073637 12613456023 032461 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.integration; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Collection; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; 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.ProtocolVersion; import org.apache.http.entity.ContentType; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.BasicAsyncRequestConsumer; import org.apache.http.nio.protocol.BasicAsyncRequestHandler; import org.apache.http.nio.protocol.BasicAsyncResponseProducer; import org.apache.http.nio.protocol.HttpAsyncExchange; import org.apache.http.nio.protocol.HttpAsyncExpectationVerifier; import org.apache.http.nio.protocol.HttpAsyncRequestConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestHandler; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.testserver.HttpCoreNIOTestBase; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; 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.util.EntityUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * HttpCore NIO integration tests for async handlers. */ @RunWith(Parameterized.class) public class TestHttpAsyncHandlers extends HttpCoreNIOTestBase { @Parameterized.Parameters(name = "{0}") public static Collection protocols() { return Arrays.asList(new Object[][]{ { ProtocolScheme.http }, { ProtocolScheme.https }, }); } public TestHttpAsyncHandlers(final ProtocolScheme scheme) { super(scheme); } @Before public void setUp() throws Exception { initServer(); initClient(); } @After public void tearDown() throws Exception { shutDownClient(); shutDownServer(); } private HttpHost start() throws IOException, InterruptedException { this.server.start(); this.client.start(); final ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); return new HttpHost("localhost", address.getPort(), getScheme().name()); } private static String createRequestUri(final String pattern, final int count) { return pattern + "x" + count; } private static String createExpectedString(final String pattern, final int count) { final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < count; i++) { buffer.append(pattern); } return buffer.toString(); } @Test public void testHttpGets() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final String expectedPattern = createExpectedString(pattern, count); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpRequest request = new BasicHttpRequest("GET", createRequestUri(pattern, count)); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(expectedPattern, EntityUtils.toString(response.getEntity())); } } @Test public void testHttpHeads() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpRequest request = new BasicHttpRequest("HEAD", createRequestUri(pattern, count)); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } } @Test public void testHttpPostsWithContentLength() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final String expectedPattern = createExpectedString(pattern, count); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri(pattern, count)); final NStringEntity entity = new NStringEntity(expectedPattern, ContentType.DEFAULT_TEXT); request.setEntity(entity); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(expectedPattern, EntityUtils.toString(response.getEntity())); } } @Test public void testHttpPostsChunked() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final String expectedPattern = createExpectedString(pattern, count); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri(pattern, count)); final NStringEntity entity = new NStringEntity(expectedPattern, ContentType.DEFAULT_TEXT); entity.setChunked(true); request.setEntity(entity); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(expectedPattern, EntityUtils.toString(response.getEntity())); } } @Test public void testHttpPostsHTTP10() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final String expectedPattern = createExpectedString(pattern, count); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri(pattern, count), HttpVersion.HTTP_1_0); final NStringEntity entity = new NStringEntity(expectedPattern, ContentType.DEFAULT_TEXT); request.setEntity(entity); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(expectedPattern, EntityUtils.toString(response.getEntity())); } } @Test public void testHttpPostsNoEntity() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri(pattern, count)); request.setEntity(null); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } } @Test public void testHttpPostNoContentLength() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); this.client.setHttpProcessor(new ImmutableHttpProcessor( new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(true))); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri(pattern, count)); request.setEntity(null); final Future future = this.client.execute(target, request); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testHttpPostIdentity() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); this.client.setHttpProcessor(new ImmutableHttpProcessor( new HttpRequestInterceptor() { @Override 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 HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri(pattern, count)); request.setEntity(null); final Future future = this.client.execute(target, request); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); } @Test public void testHttpPostsWithExpectContinue() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final String expectedPattern = createExpectedString(pattern, count); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri(pattern, count)); final NStringEntity entity = new NStringEntity(expectedPattern, ContentType.DEFAULT_TEXT); request.setEntity(entity); final HttpContext context = new BasicHttpContext(); final Future future = this.client.execute(target, request, context); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(expectedPattern, EntityUtils.toString(response.getEntity())); } } @Test public void testHttpPostsWithExpectationVerification() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); this.server.setExpectationVerifier(new HttpAsyncExpectationVerifier() { @Override public void verify( final HttpAsyncExchange httpexchange, final HttpContext context) throws HttpException { final HttpRequest request = httpexchange.getRequest(); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); final String s = request.getRequestLine().getUri(); if (!s.equals("AAAAAx10")) { if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { ver = HttpVersion.HTTP_1_1; } final BasicHttpResponse response = new BasicHttpResponse(ver, HttpStatus.SC_EXPECTATION_FAILED, "Expectation failed"); response.setEntity(new NStringEntity("Expectation failed", ContentType.TEXT_PLAIN)); httpexchange.submitResponse(new BasicAsyncResponseProducer(response)); } else { httpexchange.submitResponse(); } } }); final HttpHost target = start(); final BasicHttpEntityEnclosingRequest request1 = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri("AAAAA", 10)); request1.setEntity(new NStringEntity(createExpectedString("AAAAA", 10))); final BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri("AAAAA", 10)); request2.setEntity(new NStringEntity(createExpectedString("AAAAA", 10))); final BasicHttpEntityEnclosingRequest request3 = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri("BBBBB", 10)); request3.setEntity(new NStringEntity(createExpectedString("BBBBB", 10))); final HttpRequest[] requests = new HttpRequest[] { request1, request2, request3 }; final Queue> queue = new ConcurrentLinkedQueue>(); for (final HttpRequest request : requests) { final HttpContext context = new BasicHttpContext(); final Future future = this.client.execute(target, request, context); queue.add(future); } final Future future1 = queue.remove(); final HttpResponse response1 = future1.get(); Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode()); final Future future2 = queue.remove(); final HttpResponse response2 = future2.get(); Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode()); final Future future3 = queue.remove(); final HttpResponse response3 = future3.get(); Assert.assertEquals(HttpStatus.SC_EXPECTATION_FAILED, response3.getStatusLine().getStatusCode()); } @Test public void testHttpHeadsDelayedResponse() throws Exception { class DelayedRequestHandler implements HttpAsyncRequestHandler { private final SimpleRequestHandler requestHandler; public DelayedRequestHandler() { super(); this.requestHandler = new SimpleRequestHandler(); } @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) { return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest request, final HttpAsyncExchange httpexchange, final HttpContext context) throws HttpException, IOException { ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { ver = HttpVersion.HTTP_1_1; } final BasicHttpResponse response = new BasicHttpResponse(ver, HttpStatus.SC_OK, "OK"); new Thread() { @Override public void run() { // Wait a bit, to make sure this is delayed. try { Thread.sleep(100); } catch(final InterruptedException ie) {} // Set the entity after delaying... try { requestHandler.handle(request, response, context); } catch (final Exception ex) { response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } httpexchange.submitResponse(new BasicAsyncResponseProducer(response)); } }.start(); } } this.server.registerHandler("*", new DelayedRequestHandler()); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpRequest request = new BasicHttpRequest("HEAD", createRequestUri(pattern, count)); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } } @Test public void testHttpPostsWithExpectationVerificationDelayedResponse() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new SimpleRequestHandler())); this.server.setExpectationVerifier(new HttpAsyncExpectationVerifier() { @Override public void verify( final HttpAsyncExchange httpexchange, final HttpContext context) throws HttpException { new Thread() { @Override public void run() { // Wait a bit, to make sure this is delayed. try { Thread.sleep(100); } catch (final InterruptedException ie) { } // Set the entity after delaying... final HttpRequest request = httpexchange.getRequest(); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); final String s = request.getRequestLine().getUri(); if (!s.equals("AAAAAx10")) { if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { ver = HttpVersion.HTTP_1_1; } final BasicHttpResponse response = new BasicHttpResponse(ver, HttpStatus.SC_EXPECTATION_FAILED, "Expectation failed"); response.setEntity(new NStringEntity("Expectation failed", ContentType.TEXT_PLAIN)); httpexchange.submitResponse(new BasicAsyncResponseProducer(response)); } else { httpexchange.submitResponse(); } } }.start(); } }); final HttpHost target = start(); final BasicHttpEntityEnclosingRequest request1 = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri("AAAAA", 10)); request1.setEntity(new NStringEntity(createExpectedString("AAAAA", 10))); final BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri("AAAAA", 10)); request2.setEntity(new NStringEntity(createExpectedString("AAAAA", 10))); final BasicHttpEntityEnclosingRequest request3 = new BasicHttpEntityEnclosingRequest( "POST", createRequestUri("BBBBB", 10)); request3.setEntity(new NStringEntity(createExpectedString("BBBBB", 10))); final HttpRequest[] requests = new HttpRequest[] { request1, request2, request3 }; final Queue> queue = new ConcurrentLinkedQueue>(); for (final HttpRequest request : requests) { final HttpContext context = new BasicHttpContext(); final Future future = this.client.execute(target, request, context); queue.add(future); } final Future future1 = queue.remove(); final HttpResponse response1 = future1.get(); Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode()); final Future future2 = queue.remove(); final HttpResponse response2 = future2.get(); Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode()); final Future future3 = queue.remove(); final HttpResponse response3 = future3.get(); Assert.assertEquals(HttpStatus.SC_EXPECTATION_FAILED, response3.getStatusLine().getStatusCode()); } @Test public void testHttpExceptionInHandler() throws Exception { class FailingRequestHandler implements HttpAsyncRequestHandler { public FailingRequestHandler() { super(); } @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) { return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest request, final HttpAsyncExchange httpexchange, final HttpContext context) throws HttpException, IOException { throw new HttpException("Boom"); } } this.server.registerHandler("*", new FailingRequestHandler()); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 1; i++) { final BasicHttpRequest request = new BasicHttpRequest("GET", createRequestUri(pattern, count)); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode()); } } @Test public void testNoServiceHandler() throws Exception { final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final String pattern = RndTestPatternGenerator.generateText(); final int count = RndTestPatternGenerator.generateCount(1000); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpRequest request = new BasicHttpRequest("GET", createRequestUri(pattern, count)); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getStatusLine().getStatusCode()); } } @Test public void testResponseNoContent() throws Exception { this.server.registerHandler("*", new BasicAsyncRequestHandler(new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_NO_CONTENT); } })); final HttpHost target = start(); this.client.setMaxPerRoute(3); this.client.setMaxTotal(3); final Queue> queue = new ConcurrentLinkedQueue>(); for (int i = 0; i < 30; i++) { final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final Future future = this.client.execute(target, request); queue.add(future); } while (!queue.isEmpty()) { final Future future = queue.remove(); final HttpResponse response = future.get(); Assert.assertNotNull(response); Assert.assertNull(response.getEntity()); } } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/0040755 0000000 0000000 00000000000 12613456024 027357 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000155 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/HttpCoreNIOTestBase.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/HttpCoreNIOTestB0100644 0000000 0000000 00000007653 12613456024 032352 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.testserver; import java.net.URL; import javax.net.ssl.SSLContext; import org.apache.http.impl.nio.pool.BasicNIOConnFactory; import org.apache.http.ssl.SSLContextBuilder; import org.junit.After; /** * Base class for all HttpCore NIO integration tests * */ public abstract class HttpCoreNIOTestBase { public enum ProtocolScheme { http, https } private final ProtocolScheme scheme; protected HttpServerNio server; protected HttpClientNio client; public HttpCoreNIOTestBase(final ProtocolScheme scheme) { this.scheme = scheme; } public HttpCoreNIOTestBase() { this(ProtocolScheme.http); } public ProtocolScheme getScheme() { return this.scheme; } protected SSLContext createServerSSLContext() throws Exception { final URL keyStoreURL = getClass().getResource("/test.keystore"); final String storePassword = "nopassword"; return SSLContextBuilder.create() .loadTrustMaterial(keyStoreURL, storePassword.toCharArray()) .loadKeyMaterial(keyStoreURL, storePassword.toCharArray(), storePassword.toCharArray()) .build(); } protected SSLContext createClientSSLContext() throws Exception { final URL keyStoreURL = getClass().getResource("/test.keystore"); final String storePassword = "nopassword"; return SSLContextBuilder.create() .loadTrustMaterial(keyStoreURL, storePassword.toCharArray()) .build(); } protected ServerConnectionFactory createServerConnectionFactory() throws Exception { return new ServerConnectionFactory( this.scheme.equals(ProtocolScheme.https) ? createServerSSLContext() : null); } protected BasicNIOConnFactory createClientConnectionFactory() throws Exception { return new BasicNIOConnFactory( new ClientConnectionFactory(), this.scheme.equals(ProtocolScheme.https) ? new ClientConnectionFactory(createClientSSLContext()) : null); } public void initServer() throws Exception { this.server = new HttpServerNio(); this.server.setConnectionFactory(createServerConnectionFactory()); this.server.setTimeout(5000); } public void initClient() throws Exception { this.client = new HttpClientNio(createClientConnectionFactory()); this.client.setTimeout(5000); } @After public void shutDownClient() throws Exception { if (this.client != null) { this.client.shutdown(); this.client = null; } } @After public void shutDownServer() throws Exception { if (this.server != null) { this.server.shutdown(); this.server = null; } } } ././@LongLink0100644 0000000 0000000 00000000147 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/HttpClientNio.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/HttpClientNio.ja0100644 0000000 0000000 00000027256 12613456023 032427 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.testserver; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.OoopsieRuntimeException; import org.apache.http.concurrent.FutureCallback; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.nio.DefaultHttpClientIODispatch; import org.apache.http.impl.nio.DefaultNHttpClientConnection; import org.apache.http.impl.nio.DefaultNHttpClientConnectionFactory; import org.apache.http.impl.nio.pool.BasicNIOConnPool; import org.apache.http.impl.nio.pool.BasicNIOPoolEntry; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.ExceptionEvent; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientEventHandler; import org.apache.http.nio.pool.NIOConnFactory; import org.apache.http.nio.protocol.BasicAsyncRequestProducer; import org.apache.http.nio.protocol.BasicAsyncResponseConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestExecutor; import org.apache.http.nio.protocol.HttpAsyncRequestProducer; import org.apache.http.nio.protocol.HttpAsyncRequester; import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; 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; @SuppressWarnings("deprecation") public class HttpClientNio { public static final HttpProcessor DEFAULT_HTTP_PROC = new ImmutableHttpProcessor( new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent("TEST-CLIENT/1.1"), new RequestExpectContinue(true)); private final DefaultConnectingIOReactor ioReactor; private final BasicNIOConnPool connpool; private volatile HttpProcessor httpProcessor; private volatile HttpAsyncRequester executor; private volatile IOReactorThread thread; private volatile int timeout; public HttpClientNio( final NIOConnFactory connFactory) throws IOException { super(); this.ioReactor = new DefaultConnectingIOReactor(); this.ioReactor.setExceptionHandler(new SimpleIOReactorExceptionHandler()); this.connpool = new BasicNIOConnPool(this.ioReactor, new NIOConnFactory() { @Override public NHttpClientConnection create( final HttpHost route, final IOSession session) throws IOException { final NHttpClientConnection conn = connFactory.create(route, session); conn.setSocketTimeout(timeout); return conn; } }, 0); } public int getTimeout() { return this.timeout; } public void setTimeout(final int timeout) { this.timeout = timeout; } public void setMaxTotal(final int max) { this.connpool.setMaxTotal(max); } public void setMaxPerRoute(final int max) { this.connpool.setDefaultMaxPerRoute(max); } public void setHttpProcessor(final HttpProcessor httpProcessor) { this.httpProcessor = httpProcessor; } public Future lease( final HttpHost host, final FutureCallback callback) { return this.connpool.lease(host, null, this.timeout, TimeUnit.MILLISECONDS, callback); } public void release(final BasicNIOPoolEntry poolEntry, final boolean reusable) { this.connpool.release(poolEntry, reusable); } public Future execute( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final HttpContext context, final FutureCallback callback) { return executor.execute(requestProducer, responseConsumer, this.connpool, context != null ? context : HttpCoreContext.create(), callback); } public Future> executePipelined( final HttpHost target, final List requestProducers, final List> responseConsumers, final HttpContext context, final FutureCallback> callback) { return executor.executePipelined(target, requestProducers, responseConsumers, this.connpool, context != null ? context : HttpCoreContext.create(), callback); } public Future execute( final HttpHost target, final HttpRequest request, final HttpContext context, final FutureCallback callback) { return execute( new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), context != null ? context : HttpCoreContext.create(), callback); } public Future> executePipelined( final HttpHost target, final List requests, final HttpContext context, final FutureCallback> callback) { final List requestProducers = new ArrayList(requests.size()); final List> responseConsumers = new ArrayList>(requests.size()); for (HttpRequest request: requests) { requestProducers.add(new BasicAsyncRequestProducer(target, request)); responseConsumers.add(new BasicAsyncResponseConsumer()); } return executor.executePipelined(target, requestProducers, responseConsumers, this.connpool, context != null ? context : HttpCoreContext.create(), callback); } public Future execute( final HttpHost target, final HttpRequest request, final HttpContext context) { return execute(target, request, context, null); } public Future> executePipelined( final HttpHost target, final List requests, final HttpContext context) { return executePipelined(target, requests, context, null); } public Future execute( final HttpHost target, final HttpRequest request) { return execute(target, request, null, null); } public Future> executePipelined( final HttpHost target, final HttpRequest... requests) { return executePipelined(target, Arrays.asList(requests), null, null); } private void execute(final NHttpClientEventHandler clientHandler) throws IOException { final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(clientHandler, new DefaultNHttpClientConnectionFactory(ConnectionConfig.DEFAULT)) { @Override protected DefaultNHttpClientConnection createConnection(final IOSession session) { final DefaultNHttpClientConnection conn = super.createConnection(session); conn.setSocketTimeout(timeout); return conn; } }; this.ioReactor.execute(ioEventDispatch); } public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) { final SessionRequest sessionRequest = this.ioReactor.connect(address, null, attachment, null); sessionRequest.setConnectTimeout(this.timeout); return sessionRequest; } public void start() { this.executor = new HttpAsyncRequester(this.httpProcessor != null ? this.httpProcessor : DEFAULT_HTTP_PROC); this.thread = new IOReactorThread(new HttpAsyncRequestExecutor()); this.thread.start(); } public ConnectingIOReactor getIoReactor() { return this.ioReactor; } public IOReactorStatus getStatus() { return this.ioReactor.getStatus(); } public List getAuditLog() { return this.ioReactor.getAuditLog(); } public void join(final long timeout) throws InterruptedException { if (this.thread != null) { this.thread.join(timeout); } } public Exception getException() { if (this.thread != null) { return this.thread.getException(); } else { return null; } } public void shutdown() throws IOException { this.connpool.shutdown(2000); try { join(500); } catch (final InterruptedException ignore) { } } private class IOReactorThread extends Thread { private final NHttpClientEventHandler clientHandler; private volatile Exception ex; public IOReactorThread(final NHttpClientEventHandler clientHandler) { super(); this.clientHandler = clientHandler; } @Override public void run() { try { execute(this.clientHandler); } catch (final Exception ex) { this.ex = ex; } } public Exception getException() { return this.ex; } } static class SimpleIOReactorExceptionHandler implements IOReactorExceptionHandler { @Override public boolean handle(final RuntimeException ex) { if (!(ex instanceof OoopsieRuntimeException)) { ex.printStackTrace(System.out); } return false; } @Override public boolean handle(final IOException ex) { ex.printStackTrace(System.out); return false; } } } ././@LongLink0100644 0000000 0000000 00000000161 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/ServerConnectionFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/ServerConnection0100644 0000000 0000000 00000005210 12613456024 032563 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.testserver; import javax.net.ssl.SSLContext; import org.apache.http.impl.nio.DefaultNHttpServerConnection; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ssl.SSLIOSession; import org.apache.http.nio.reactor.ssl.SSLMode; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; public class ServerConnectionFactory implements NHttpConnectionFactory { private final SSLContext sslcontext; private final SSLSetupHandler setupHandler; public ServerConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler setupHandler) { super(); this.sslcontext = sslcontext; this.setupHandler = setupHandler; } public ServerConnectionFactory(final SSLContext sslcontext) { this(sslcontext, null); } public ServerConnectionFactory() { this(null, null); } @Override public DefaultNHttpServerConnection createConnection(final IOSession iosession) { if (this.sslcontext != null) { final SSLIOSession ssliosession = new SSLIOSession( iosession, SSLMode.SERVER, this.sslcontext, this.setupHandler); iosession.setAttribute(SSLIOSession.SESSION_KEY, ssliosession); return new LoggingNHttpServerConnection(ssliosession); } else { return new LoggingNHttpServerConnection(iosession); } } } ././@LongLink0100644 0000000 0000000 00000000147 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/HttpServerNio.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/HttpServerNio.ja0100644 0000000 0000000 00000012016 12613456024 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.nio.testserver; import java.io.IOException; import java.net.SocketException; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.ConnectionClosedException; import org.apache.http.ExceptionLogger; import org.apache.http.impl.nio.DefaultNHttpServerConnection; import org.apache.http.impl.nio.bootstrap.HttpServer; import org.apache.http.impl.nio.bootstrap.ServerBootstrap; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.protocol.HttpAsyncExpectationVerifier; import org.apache.http.nio.protocol.HttpAsyncRequestHandler; import org.apache.http.nio.protocol.UriHttpAsyncRequestHandlerMapper; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Asserts; public class HttpServerNio { private final UriHttpAsyncRequestHandlerMapper reqistry; private volatile HttpAsyncExpectationVerifier expectationVerifier; private volatile NHttpConnectionFactory connectionFactory; private volatile HttpProcessor httpProcessor; private volatile int timeout; private volatile HttpServer server; public HttpServerNio() throws IOException { super(); this.reqistry = new UriHttpAsyncRequestHandlerMapper(); } public int getTimeout() { return this.timeout; } public void setTimeout(final int timeout) { this.timeout = timeout; } public void registerHandler( final String pattern, final HttpAsyncRequestHandler handler) { this.reqistry.register(pattern, handler); } public void setExpectationVerifier(final HttpAsyncExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; } public void setConnectionFactory(final NHttpConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public void setHttpProcessor(final HttpProcessor httpProcessor) { this.httpProcessor = httpProcessor; } public ListenerEndpoint getListenerEndpoint() { final HttpServer local = this.server; if (local != null) { return this.server.getEndpoint(); } else { throw new IllegalStateException("Server not running"); } } public void start() throws IOException { Asserts.check(this.server == null, "Server already running"); this.server = ServerBootstrap.bootstrap() .setIOReactorConfig(IOReactorConfig.custom() .setSoTimeout(this.timeout) .build()) .setServerInfo("TEST-SERVER/1.1") .setConnectionFactory(connectionFactory) .setExceptionLogger(new SimpleExceptionLogger()) .setExpectationVerifier(this.expectationVerifier) .setHttpProcessor(this.httpProcessor) .setHandlerMapper(this.reqistry) .create(); this.server.start(); } public void shutdown() { final HttpServer local = this.server; this.server = null; if (local != null) { local.shutdown(5, TimeUnit.SECONDS); } } static class SimpleExceptionLogger implements ExceptionLogger { private final Log log = LogFactory.getLog(HttpServer.class); @Override public void log(final Exception ex) { if (ex instanceof ConnectionClosedException) { this.log.debug(ex.getMessage()); } else if (ex instanceof SocketException) { this.log.debug(ex.getMessage()); } else { this.log.error(ex.getMessage(), ex); } } } } ././@LongLink0100644 0000000 0000000 00000000161 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/ClientConnectionFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/ClientConnection0100644 0000000 0000000 00000005210 12613456023 032532 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.testserver; import javax.net.ssl.SSLContext; import org.apache.http.impl.nio.DefaultNHttpClientConnection; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ssl.SSLIOSession; import org.apache.http.nio.reactor.ssl.SSLMode; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; public class ClientConnectionFactory implements NHttpConnectionFactory { private final SSLContext sslcontext; private final SSLSetupHandler setupHandler; public ClientConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler setupHandler) { super(); this.sslcontext = sslcontext; this.setupHandler = setupHandler; } public ClientConnectionFactory(final SSLContext sslcontext) { this(sslcontext, null); } public ClientConnectionFactory() { this(null, null); } @Override public DefaultNHttpClientConnection createConnection(final IOSession iosession) { if (this.sslcontext != null) { final SSLIOSession ssliosession = new SSLIOSession( iosession, SSLMode.CLIENT, this.sslcontext, this.setupHandler); iosession.setAttribute(SSLIOSession.SESSION_KEY, ssliosession); return new LoggingNHttpClientConnection(ssliosession); } else { return new LoggingNHttpClientConnection(iosession); } } } ././@LongLink0100644 0000000 0000000 00000000152 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/LoggingIOSession.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/LoggingIOSession0100644 0000000 0000000 00000016724 12613456023 032472 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.testserver; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import org.apache.commons.logging.Log; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionBufferStatus; /** * Decorator class intended to transparently extend an {@link IOSession} * with basic event logging capabilities using Commons Logging. * */ public class LoggingIOSession implements IOSession { private final Log log; private final Wire wirelog; private final String id; private final IOSession session; private final ByteChannel channel; public LoggingIOSession(final IOSession session, final String id, final Log log, final Log wirelog) { super(); this.session = session; this.channel = new LoggingByteChannel(); this.id = id; this.log = log; this.wirelog = new Wire(wirelog, this.id); } @Override public ByteChannel channel() { return this.channel; } @Override public SocketAddress getLocalAddress() { return this.session.getLocalAddress(); } @Override public SocketAddress getRemoteAddress() { return this.session.getRemoteAddress(); } @Override public int getEventMask() { return this.session.getEventMask(); } private static String formatOps(final int ops) { final StringBuilder buffer = new StringBuilder(6); buffer.append('['); if ((ops & SelectionKey.OP_READ) > 0) { buffer.append('r'); } if ((ops & SelectionKey.OP_WRITE) > 0) { buffer.append('w'); } if ((ops & SelectionKey.OP_ACCEPT) > 0) { buffer.append('a'); } if ((ops & SelectionKey.OP_CONNECT) > 0) { buffer.append('c'); } buffer.append(']'); return buffer.toString(); } @Override public void setEventMask(final int ops) { this.session.setEventMask(ops); if (this.log.isDebugEnabled()) { this.log.debug(this.id + " " + this.session + ": Event mask set " + formatOps(ops)); } } @Override public void setEvent(final int op) { this.session.setEvent(op); if (this.log.isDebugEnabled()) { this.log.debug(this.id + " " + this.session + ": Event set " + formatOps(op)); } } @Override public void clearEvent(final int op) { this.session.clearEvent(op); if (this.log.isDebugEnabled()) { this.log.debug(this.id + " " + this.session + ": Event cleared " + formatOps(op)); } } @Override public void close() { if (this.log.isDebugEnabled()) { this.log.debug(this.id + " " + this.session + ": Close"); } this.session.close(); } @Override public int getStatus() { return this.session.getStatus(); } @Override public boolean isClosed() { return this.session.isClosed(); } @Override public void shutdown() { if (this.log.isDebugEnabled()) { this.log.debug(this.id + " " + this.session + ": Shutdown"); } this.session.shutdown(); } @Override public int getSocketTimeout() { return this.session.getSocketTimeout(); } @Override public void setSocketTimeout(final int timeout) { if (this.log.isDebugEnabled()) { this.log.debug(this.id + " " + this.session + ": Set timeout " + timeout); } this.session.setSocketTimeout(timeout); } @Override public void setBufferStatus(final SessionBufferStatus status) { this.session.setBufferStatus(status); } @Override public boolean hasBufferedInput() { return this.session.hasBufferedInput(); } @Override public boolean hasBufferedOutput() { return this.session.hasBufferedOutput(); } @Override public Object getAttribute(final String name) { return this.session.getAttribute(name); } @Override public void setAttribute(final String name, final Object obj) { if (this.log.isDebugEnabled()) { this.log.debug(this.id + " " + this.session + ": Set attribute " + name); } this.session.setAttribute(name, obj); } @Override public Object removeAttribute(final String name) { if (this.log.isDebugEnabled()) { this.log.debug(this.id + " " + this.session + ": Remove attribute " + name); } return this.session.removeAttribute(name); } @Override public String toString() { return this.id + " " + this.session.toString(); } class LoggingByteChannel implements ByteChannel { @Override public int read(final ByteBuffer dst) throws IOException { final int bytesRead = session.channel().read(dst); if (log.isDebugEnabled()) { log.debug(id + " " + session + ": " + bytesRead + " bytes read"); } if (bytesRead > 0 && wirelog.isEnabled()) { final ByteBuffer b = dst.duplicate(); final int p = b.position(); b.limit(p); b.position(p - bytesRead); wirelog.input(b); } return bytesRead; } @Override public int write(final ByteBuffer src) throws IOException { final int byteWritten = session.channel().write(src); if (log.isDebugEnabled()) { log.debug(id + " " + session + ": " + byteWritten + " bytes written"); } if (byteWritten > 0 && wirelog.isEnabled()) { final ByteBuffer b = src.duplicate(); final int p = b.position(); b.limit(p); b.position(p - byteWritten); wirelog.output(b); } return byteWritten; } @Override public void close() throws IOException { if (log.isDebugEnabled()) { log.debug(id + " " + session + ": Channel close"); } session.channel().close(); } @Override public boolean isOpen() { return session.channel().isOpen(); } } } ././@LongLink0100644 0000000 0000000 00000000166 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/LoggingNHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/LoggingNHttpClie0100644 0000000 0000000 00000011204 12613456023 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.nio.testserver; import java.io.IOException; 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.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.impl.nio.DefaultNHttpClientConnection; import org.apache.http.nio.NHttpClientEventHandler; import org.apache.http.nio.reactor.IOSession; public class LoggingNHttpClientConnection extends DefaultNHttpClientConnection { private static final AtomicLong COUNT = new AtomicLong(); private final Log log; private final Log iolog; private final Log headerlog; private final Log wirelog; private final String id; public LoggingNHttpClientConnection(final IOSession session) { super(session, 8 * 1024); this.log = LogFactory.getLog(getClass()); this.iolog = LogFactory.getLog(session.getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); this.wirelog = LogFactory.getLog("org.apache.http.wire"); this.id = "http-outgoing-" + COUNT.incrementAndGet(); if (this.iolog.isDebugEnabled() || this.wirelog.isDebugEnabled()) { this.session = new LoggingIOSession(session, this.id, this.iolog, this.wirelog); } } @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 public void submitRequest(final HttpRequest request) throws IOException, HttpException { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": " + request.getRequestLine().toString()); } super.submitRequest(request); } @Override public void consumeInput(final NHttpClientEventHandler handler) { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": Consume input"); } super.consumeInput(handler); } @Override public void produceOutput(final NHttpClientEventHandler handler) { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": Produce output"); } super.produceOutput(handler); } @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()); } } } @Override public String toString() { return this.id; } } ././@LongLink0100644 0000000 0000000 00000000166 12613460516 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/LoggingNHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/LoggingNHttpServ0100644 0000000 0000000 00000011216 12613456024 032504 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.testserver; import java.io.IOException; 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.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.impl.nio.DefaultNHttpServerConnection; import org.apache.http.nio.NHttpServerEventHandler; import org.apache.http.nio.reactor.IOSession; public class LoggingNHttpServerConnection extends DefaultNHttpServerConnection { private static final AtomicLong COUNT = new AtomicLong(); private final Log log; private final Log iolog; private final Log headerlog; private final Log wirelog; private final String id; public LoggingNHttpServerConnection(final IOSession session) { super(session, 8 * 1024); this.log = LogFactory.getLog(getClass()); this.iolog = LogFactory.getLog(session.getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); this.wirelog = LogFactory.getLog("org.apache.http.wire"); this.id = "http-incoming-" + COUNT.incrementAndGet(); if (this.iolog.isDebugEnabled() || this.wirelog.isDebugEnabled()) { this.session = new LoggingIOSession(session, this.id, this.iolog, this.wirelog); } } @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 public void submitResponse(final HttpResponse response) throws IOException, HttpException { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": " + response.getStatusLine().toString()); } super.submitResponse(response); } @Override public void consumeInput(final NHttpServerEventHandler handler) { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": Consume input"); } super.consumeInput(handler); } @Override public void produceOutput(final NHttpServerEventHandler handler) { if (this.log.isDebugEnabled()) { this.log.debug(this.id + ": Produce output"); } super.produceOutput(handler); } @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()); } } } @Override public String toString() { return this.id; } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/nio/testserver/Wire.java0100644 0000000 0000000 00000007263 12613456023 031134 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.testserver; import java.nio.ByteBuffer; 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}); } public void output(final ByteBuffer b) { if (b.hasArray()) { output(b.array(), b.arrayOffset() + b.position(), b.remaining()); } else { final byte[] tmp = new byte[b.remaining()]; b.get(tmp); output(tmp); } } public void input(final ByteBuffer b) { if (b.hasArray()) { input(b.array(), b.arrayOffset() + b.position(), b.remaining()); } else { final byte[] tmp = new byte[b.remaining()]; b.get(tmp); input(tmp); } } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/0040755 0000000 0000000 00000000000 12613456023 025324 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/0040755 0000000 0000000 00000000000 12613456023 026111 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000164 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestDefaultNHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestDefaultNHttpServer0100644 0000000 0000000 00000072662 12613456023 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.nio; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.util.LinkedList; import org.apache.http.ByteChannelMock; import org.apache.http.Consts; 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.ReadableByteChannelMock; import org.apache.http.WritableByteChannelMock; import org.apache.http.entity.StringEntity; import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.NHttpServerEventHandler; import org.apache.http.nio.entity.HttpAsyncContentProducer; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.SimpleInputBuffer; import org.apache.http.protocol.HTTP; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class TestDefaultNHttpServerConnection { @Mock private IOSession session; @Mock private ByteChannel byteChan; @Mock private NHttpServerEventHandler handler; private DefaultNHttpServerConnection conn; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); conn = new DefaultNHttpServerConnection(session, 32); } @Test public void testSubmitRequest() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); conn.submitResponse(response); Assert.assertNull(conn.getHttpResponse()); Assert.assertTrue(conn.hasBufferedOutput()); Mockito.verify(session).setEvent(SelectionKey.OP_WRITE); } @Test public void testSubmitEntityEnclosingRequest() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.setEntity(new StringEntity("stuff")); Mockito.when(session.channel()).thenReturn(byteChan); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); conn.submitResponse(response); Assert.assertSame(response, conn.getHttpResponse()); Assert.assertTrue(conn.hasBufferedOutput()); Assert.assertTrue(conn.isResponseSubmitted()); Assert.assertNotNull(conn.contentEncoder); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); Mockito.verify(session).setEvent(SelectionKey.OP_WRITE); } @Test public void testOutputReset() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.setEntity(new StringEntity("stuff")); Mockito.when(session.channel()).thenReturn(byteChan); conn.submitResponse(response); Assert.assertNotNull(conn.getHttpResponse()); Assert.assertNotNull(conn.contentEncoder); conn.resetOutput(); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentEncoder); } static class ResponseReadyAnswer implements Answer { private final HttpResponse response; ResponseReadyAnswer(final HttpResponse response) { super(); this.response = response; } @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final NHttpServerConnection conn = (NHttpServerConnection) args[0]; conn.submitResponse(response); return null; } } static class ProduceContentAnswer implements Answer { private final HttpAsyncContentProducer contentProducer; ProduceContentAnswer(final HttpAsyncContentProducer contentProducer) { super(); this.contentProducer = contentProducer; } @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final IOControl ioctrl = (IOControl) args[0]; final ContentEncoder encoder = (ContentEncoder) args[1]; contentProducer.produceContent(encoder, ioctrl); return null; } } @Test public void testProduceOutputShortMessageAfterSubmit() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final NStringEntity entity = new NStringEntity("stuff"); response.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); conn.submitResponse(response); Assert.assertEquals(19, conn.outbuf.length()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\nstuff", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.any()); } @Test public void testProduceOutputLongMessageAfterSubmit() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final NStringEntity entity = new NStringEntity("a lot of various stuff"); response.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); conn.submitResponse(response); Assert.assertEquals(19, conn.outbuf.length()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputShortMessage() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final NStringEntity entity = new NStringEntity("stuff"); response.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new ResponseReadyAnswer(response)).when( handler).responseReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\nstuff", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.any()); } @Test public void testProduceOutputLongMessage() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final NStringEntity entity = new NStringEntity("a lot of various stuff"); response.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new ResponseReadyAnswer(response)).when( handler).responseReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputLongMessageSaturatedChannel() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final NStringEntity entity = new NStringEntity("a lot of various stuff"); response.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new ResponseReadyAnswer(response)).when( handler).responseReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\na lot", wchannel.dump(Consts.ASCII)); Assert.assertEquals(17, conn.outbuf.length()); Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputLongMessageSaturatedChannel2() throws Exception { conn = new DefaultNHttpServerConnection(session, 24); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final NStringEntity entity = new NStringEntity("a loooooooooooooooooooooooot of various stuff"); response.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new ResponseReadyAnswer(response)).when( handler).responseReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNotNull(conn.getHttpResponse()); Assert.assertNotNull(conn.contentEncoder); Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\na loo", wchannel.dump(Consts.ASCII)); Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE); Mockito.verify(wchannel, Mockito.times(3)).write(Matchers.any()); } @Test public void testProduceOutputLongChunkedMessage() throws Exception { conn = new DefaultNHttpServerConnection(session, 64); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); final NStringEntity entity = new NStringEntity("a lot of various stuff"); entity.setChunked(true); response.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new ResponseReadyAnswer(response)).when( handler).responseReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "5\r\na lot\r\n11\r\n of various stuff\r\n0\r\n\r\n", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputLongChunkedMessageSaturatedChannel() throws Exception { conn = new DefaultNHttpServerConnection(session, 64); final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); final NStringEntity entity = new NStringEntity("a lot of various stuff"); entity.setChunked(true); response.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new ResponseReadyAnswer(response)).when( handler).responseReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "5\r\na lot\r\n11\r\n of", wchannel.dump(Consts.ASCII)); Assert.assertEquals(21, conn.outbuf.length()); Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputClosingConnection() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); conn.submitResponse(response); conn.close(); Assert.assertEquals(NHttpConnection.CLOSING, conn.getStatus()); conn.produceOutput(handler); Assert.assertEquals(NHttpConnection.CLOSED, conn.getStatus()); Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.any()); Mockito.verify(session, Mockito.times(1)).close(); Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE); Mockito.verify(handler, Mockito.never()).responseReady( Mockito.any()); Mockito.verify(handler, Mockito.never()).outputReady( Mockito.any(), Mockito.any()); } static class RequestCapturingAnswer implements Answer { private final LinkedList requests; RequestCapturingAnswer(final LinkedList requests) { super(); this.requests = requests; } @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final NHttpServerConnection conn = (NHttpServerConnection) args[0]; if (conn != null) { final HttpRequest request = conn.getHttpRequest(); if (request != null) { requests.add(request); } } return null; } } static class ConsumeContentAnswer implements Answer { private final SimpleInputBuffer buf; ConsumeContentAnswer(final SimpleInputBuffer buf) { super(); this.buf = buf; } @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final ContentDecoder decoder = (ContentDecoder) args[1]; buf.consumeContent(decoder); return null; } } @Test public void testConsumeInputShortMessage() throws Exception { final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"POST / HTTP/1.1\r\nContent-Length: 5\r\n\r\nstuff"}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); final LinkedList requests = new LinkedList(); Mockito.doAnswer(new RequestCapturingAnswer(requests)).when( handler).requestReceived(Mockito.any()); Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when( handler).inputReady(Mockito.any(), Mockito.any()); Assert.assertEquals(0, conn.getMetrics().getRequestCount()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); Assert.assertEquals(43, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.times(1)).requestReceived( Mockito.any()); Mockito.verify(handler, Mockito.times(1)).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); Assert.assertFalse(requests.isEmpty()); final HttpRequest request = requests.getFirst(); Assert.assertNotNull(request); Assert.assertEquals(HttpVersion.HTTP_1_1, request.getRequestLine().getProtocolVersion()); Assert.assertEquals("POST", request.getRequestLine().getMethod()); Assert.assertEquals("/", request.getRequestLine().getUri()); Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); Assert.assertNotNull(entity); Assert.assertEquals(5, entity.getContentLength()); } @Test public void testConsumeInputLongMessage() throws Exception { conn = new DefaultNHttpServerConnection(session, 1024); final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"POST / HTTP/1.1\r\nContent-Length: 100\r\n\r\na lot of stuff", "", ""}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); final LinkedList requests = new LinkedList(); Mockito.doAnswer(new RequestCapturingAnswer(requests)).when( handler).requestReceived(Mockito.any()); Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when( handler).inputReady(Mockito.any(), Mockito.any()); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); conn.consumeInput(handler); Assert.assertNotNull(conn.getHttpRequest()); Assert.assertNotNull(conn.contentDecoder); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); Assert.assertEquals(54, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.times(1)).requestReceived( Mockito.any()); Mockito.verify(handler, Mockito.times(1)).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); Assert.assertFalse(requests.isEmpty()); final HttpRequest request = requests.getFirst(); Assert.assertNotNull(request); Assert.assertEquals(HttpVersion.HTTP_1_1, request.getRequestLine().getProtocolVersion()); Assert.assertEquals("POST", request.getRequestLine().getMethod()); Assert.assertEquals("/", request.getRequestLine().getUri()); Assert.assertTrue(request instanceof HttpEntityEnclosingRequest); final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); Assert.assertNotNull(entity); Assert.assertEquals(100, entity.getContentLength()); conn.consumeInput(handler); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); Assert.assertEquals(54, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(rchannel, Mockito.times(3)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); } @Test public void testConsumeInputBasicMessageNoEntity() throws Exception { final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"GET / HTTP/1.1\r\n\r\n"}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); final LinkedList requests = new LinkedList(); Mockito.doAnswer(new RequestCapturingAnswer(requests)).when( handler).requestReceived(Mockito.any()); Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when( handler).inputReady(Mockito.any(), Mockito.any()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Mockito.verify(handler, Mockito.times(1)).requestReceived( Mockito.any()); Mockito.verify(handler, Mockito.never()).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(1)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); Assert.assertFalse(requests.isEmpty()); final HttpRequest request = requests.getFirst(); Assert.assertNotNull(request); Assert.assertEquals(HttpVersion.HTTP_1_1, request.getRequestLine().getProtocolVersion()); Assert.assertEquals("GET", request.getRequestLine().getMethod()); Assert.assertEquals("/", request.getRequestLine().getUri()); Assert.assertFalse(request instanceof HttpEntityEnclosingRequest); } @Test public void testConsumeInputNoData() throws Exception { conn = new DefaultNHttpServerConnection(session, 1024); final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"", ""}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); final LinkedList requests = new LinkedList(); Mockito.doAnswer(new RequestCapturingAnswer(requests)).when( handler).requestReceived(Mockito.any()); Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when( handler).inputReady(Mockito.any(), Mockito.any()); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.never()).requestReceived( Mockito.any()); Mockito.verify(handler, Mockito.never()).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(1)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.never()).requestReceived( Mockito.any()); Mockito.verify(handler, Mockito.never()).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.never()).requestReceived( Mockito.any()); Mockito.verify(handler, Mockito.never()).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(3)).read(Mockito.any()); Mockito.verify(handler, Mockito.times(1)).endOfInput( Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); } @Test public void testConsumeInputConnectionClosed() throws Exception { conn = new DefaultNHttpServerConnection(session, 1024); final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"", ""}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); conn.close(); conn.consumeInput(handler); Mockito.verify(rchannel, Mockito.never()).read(Mockito.any()); Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_READ); } } ././@LongLink0100644 0000000 0000000 00000000164 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestDefaultNHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestDefaultNHttpClient0100644 0000000 0000000 00000072351 12613456023 032402 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.util.LinkedList; import org.apache.http.ByteChannelMock; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.ReadableByteChannelMock; import org.apache.http.WritableByteChannelMock; import org.apache.http.entity.StringEntity; import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientEventHandler; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.entity.HttpAsyncContentProducer; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.SimpleInputBuffer; import org.apache.http.protocol.HTTP; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class TestDefaultNHttpClientConnection { @Mock private IOSession session; @Mock private ByteChannel byteChan; @Mock private NHttpClientEventHandler handler; private DefaultNHttpClientConnection conn; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); conn = new DefaultNHttpClientConnection(session, 32); } @Test public void testSubmitRequest() throws Exception { final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); conn.submitRequest(request); Assert.assertNull(conn.getHttpRequest()); Assert.assertTrue(conn.hasBufferedOutput()); Mockito.verify(session).setEvent(SelectionKey.OP_WRITE); } @Test public void testSubmitEntityEnclosingRequest() throws Exception { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setEntity(new StringEntity("stuff")); Mockito.when(session.channel()).thenReturn(byteChan); Assert.assertEquals(0, conn.getMetrics().getRequestCount()); conn.submitRequest(request); Assert.assertSame(request, conn.getHttpRequest()); Assert.assertTrue(conn.hasBufferedOutput()); Assert.assertTrue(conn.isRequestSubmitted()); Assert.assertNotNull(conn.contentEncoder); Assert.assertEquals(1, conn.getMetrics().getRequestCount()); Mockito.verify(session).setEvent(SelectionKey.OP_WRITE); } @Test public void testOutputReset() throws Exception { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.setEntity(new StringEntity("stuff")); Mockito.when(session.channel()).thenReturn(byteChan); conn.submitRequest(request); Assert.assertNotNull(conn.getHttpRequest()); Assert.assertNotNull(conn.contentEncoder); conn.resetOutput(); Assert.assertNull(conn.getHttpRequest()); Assert.assertNull(conn.contentEncoder); } static class RequestReadyAnswer implements Answer { private final HttpRequest request; RequestReadyAnswer(final HttpRequest request) { super(); this.request = request; } @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final NHttpClientConnection conn = (NHttpClientConnection) args[0]; conn.submitRequest(request); return null; } } static class ProduceContentAnswer implements Answer { private final HttpAsyncContentProducer contentProducer; ProduceContentAnswer(final HttpAsyncContentProducer contentProducer) { super(); this.contentProducer = contentProducer; } @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final IOControl ioctrl = (IOControl) args[0]; final ContentEncoder encoder = (ContentEncoder) args[1]; contentProducer.produceContent(encoder, ioctrl); return null; } } @Test public void testProduceOutputShortMessageAfterSubmit() throws Exception { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final NStringEntity entity = new NStringEntity("stuff"); request.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); conn.submitRequest(request); Assert.assertEquals(19, conn.outbuf.length()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpRequest()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("POST / HTTP/1.1\r\n\r\nstuff", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.any()); } @Test public void testProduceOutputLongMessageAfterSubmit() throws Exception { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final NStringEntity entity = new NStringEntity("a lot of various stuff"); request.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); conn.submitRequest(request); Assert.assertEquals(19, conn.outbuf.length()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpRequest()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputShortMessage() throws Exception { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final NStringEntity entity = new NStringEntity("stuff"); request.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new RequestReadyAnswer(request)).when( handler).requestReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpRequest()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("POST / HTTP/1.1\r\n\r\nstuff", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.any()); } @Test public void testProduceOutputLongMessage() throws Exception { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final NStringEntity entity = new NStringEntity("a lot of various stuff"); request.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new RequestReadyAnswer(request)).when( handler).requestReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpRequest()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputLongMessageSaturatedChannel() throws Exception { final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final NStringEntity entity = new NStringEntity("a lot of various stuff"); request.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new RequestReadyAnswer(request)).when( handler).requestReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpRequest()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot", wchannel.dump(Consts.ASCII)); Assert.assertEquals(17, conn.outbuf.length()); Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputLongMessageSaturatedChannel2() throws Exception { conn = new DefaultNHttpClientConnection(session, 24); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); final NStringEntity entity = new NStringEntity("a loooooooooooooooooooooooot of various stuff"); request.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new RequestReadyAnswer(request)).when( handler).requestReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNotNull(conn.getHttpRequest()); Assert.assertNotNull(conn.contentEncoder); Assert.assertEquals("POST / HTTP/1.1\r\n\r\na loo", wchannel.dump(Consts.ASCII)); Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE); Mockito.verify(wchannel, Mockito.times(3)).write(Matchers.any()); } @Test public void testProduceOutputLongChunkedMessage() throws Exception { conn = new DefaultNHttpClientConnection(session, 64); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); final NStringEntity entity = new NStringEntity("a lot of various stuff"); entity.setChunked(true); request.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new RequestReadyAnswer(request)).when( handler).requestReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpRequest()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" + "5\r\na lot\r\n11\r\n of various stuff\r\n0\r\n\r\n", wchannel.dump(Consts.ASCII)); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputLongChunkedMessageSaturatedChannel() throws Exception { conn = new DefaultNHttpClientConnection(session, 64); final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); final NStringEntity entity = new NStringEntity("a lot of various stuff"); entity.setChunked(true); request.setEntity(entity); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); Mockito.doAnswer(new RequestReadyAnswer(request)).when( handler).requestReady(Mockito.any()); Mockito.doAnswer(new ProduceContentAnswer(entity)).when( handler).outputReady(Mockito.any(), Mockito.any()); conn.produceOutput(handler); Assert.assertNull(conn.getHttpRequest()); Assert.assertNull(conn.contentEncoder); Assert.assertEquals("POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" + "5\r\na lot\r\n11\r\n of", wchannel.dump(Consts.ASCII)); Assert.assertEquals(21, conn.outbuf.length()); Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE); Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.any()); } @Test public void testProduceOutputClosingConnection() throws Exception { final BasicHttpRequest request = new BasicHttpRequest("GET", "/"); final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64)); final ByteChannelMock channel = new ByteChannelMock(null, wchannel); Mockito.when(session.channel()).thenReturn(channel); conn.submitRequest(request); conn.close(); Assert.assertEquals(NHttpConnection.CLOSING, conn.getStatus()); conn.produceOutput(handler); Assert.assertEquals(NHttpConnection.CLOSED, conn.getStatus()); Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.any()); Mockito.verify(session, Mockito.times(1)).close(); Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE); Mockito.verify(handler, Mockito.never()).requestReady( Mockito.any()); Mockito.verify(handler, Mockito.never()).outputReady( Mockito.any(), Mockito.any()); } static class ResponseCapturingAnswer implements Answer { private final LinkedList responses; ResponseCapturingAnswer(final LinkedList responses) { super(); this.responses = responses; } @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final NHttpClientConnection conn = (NHttpClientConnection) args[0]; if (conn != null) { final HttpResponse response = conn.getHttpResponse(); if (response != null) { responses.add(response); } } return null; } } static class ConsumeContentAnswer implements Answer { private final SimpleInputBuffer buf; ConsumeContentAnswer(final SimpleInputBuffer buf) { super(); this.buf = buf; } @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final ContentDecoder decoder = (ContentDecoder) args[1]; buf.consumeContent(decoder); return null; } } @Test public void testConsumeInputShortMessage() throws Exception { final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nstuff"}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); final LinkedList responses = new LinkedList(); Mockito.doAnswer(new ResponseCapturingAnswer(responses)).when( handler).responseReceived(Mockito.any()); Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when( handler).inputReady(Mockito.any(), Mockito.any()); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); Assert.assertEquals(43, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.times(1)).responseReceived( Mockito.any()); Mockito.verify(handler, Mockito.times(1)).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); Assert.assertFalse(responses.isEmpty()); final HttpResponse response = responses.getFirst(); Assert.assertNotNull(response); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertEquals("OK", response.getStatusLine().getReasonPhrase()); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertEquals(5, entity.getContentLength()); } @Test public void testConsumeInputLongMessage() throws Exception { conn = new DefaultNHttpClientConnection(session, 1024); final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\na lot of stuff", "", ""}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); final LinkedList responses = new LinkedList(); Mockito.doAnswer(new ResponseCapturingAnswer(responses)).when( handler).responseReceived(Mockito.any()); Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when( handler).inputReady(Mockito.any(), Mockito.any()); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); conn.consumeInput(handler); Assert.assertNotNull(conn.getHttpResponse()); Assert.assertNotNull(conn.contentDecoder); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); Assert.assertEquals(54, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.times(1)).responseReceived( Mockito.any()); Mockito.verify(handler, Mockito.times(1)).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); Assert.assertFalse(responses.isEmpty()); final HttpResponse response = responses.getFirst(); Assert.assertNotNull(response); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertEquals("OK", response.getStatusLine().getReasonPhrase()); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertEquals(100, entity.getContentLength()); conn.consumeInput(handler); Assert.assertEquals(1, conn.getMetrics().getResponseCount()); Assert.assertEquals(54, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(rchannel, Mockito.times(3)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); } @Test public void testConsumeInputBasicMessageNoEntity() throws Exception { final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"HTTP/1.1 100 Continue\r\n\r\n"}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); final LinkedList responses = new LinkedList(); Mockito.doAnswer(new ResponseCapturingAnswer(responses)).when( handler).responseReceived(Mockito.any()); Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when( handler).inputReady(Mockito.any(), Mockito.any()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Mockito.verify(handler, Mockito.times(1)).responseReceived( Mockito.any()); Mockito.verify(handler, Mockito.never()).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(1)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); Assert.assertFalse(responses.isEmpty()); final HttpResponse response = responses.getFirst(); Assert.assertNotNull(response); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion()); Assert.assertEquals(100, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); Assert.assertNull(entity); } @Test public void testConsumeInputNoData() throws Exception { conn = new DefaultNHttpClientConnection(session, 1024); final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"", ""}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); final LinkedList responses = new LinkedList(); Mockito.doAnswer(new ResponseCapturingAnswer(responses)).when( handler).responseReceived(Mockito.any()); Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when( handler).inputReady(Mockito.any(), Mockito.any()); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.never()).responseReceived( Mockito.any()); Mockito.verify(handler, Mockito.never()).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(1)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.never()).responseReceived( Mockito.any()); Mockito.verify(handler, Mockito.never()).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); conn.consumeInput(handler); Assert.assertNull(conn.getHttpResponse()); Assert.assertNull(conn.contentDecoder); Assert.assertEquals(0, conn.getMetrics().getResponseCount()); Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount()); Mockito.verify(handler, Mockito.never()).responseReceived( Mockito.any()); Mockito.verify(handler, Mockito.never()).inputReady( Mockito.any(), Mockito.any()); Mockito.verify(rchannel, Mockito.times(3)).read(Mockito.any()); Mockito.verify(handler, Mockito.times(1)).endOfInput( Mockito.any()); Mockito.verify(handler, Mockito.never()).exception( Mockito.any(), Mockito.any()); } @Test public void testConsumeInputConnectionClosed() throws Exception { conn = new DefaultNHttpClientConnection(session, 1024); final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock( new String[] {"", ""}, Consts.ASCII)); final ByteChannelMock channel = new ByteChannelMock(rchannel, null); Mockito.when(session.channel()).thenReturn(channel); Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ); conn.close(); conn.consumeInput(handler); Mockito.verify(rchannel, Mockito.never()).read(Mockito.any()); Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_READ); } } ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestContentChannel.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestContentChannel.jav0100644 0000000 0000000 00000005016 12613456023 032355 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.nio.ByteBuffer; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentDecoderChannel; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.ContentEncoderChannel; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class TestContentChannel { @Mock private ContentDecoder decoder; @Mock private ContentEncoder encoder; @Mock private ByteBuffer bb; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @After public void tearDown() throws Exception { } @Test public void testContentDecoder() throws Exception { final ContentDecoderChannel cdc = new ContentDecoderChannel(decoder); cdc.read(bb); verify(decoder, times(1)).read(bb); assertTrue(cdc.isOpen()); cdc.close(); } @Test public void testContentEncoder() throws Exception { final ContentEncoderChannel cec = new ContentEncoderChannel(encoder); cec.write(bb); verify(encoder, times(1)).write(bb); assertTrue(cec.isOpen()); cec.close(); } } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestNHttpConnectionBase.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestNHttpConnectionBas0100644 0000000 0000000 00000026203 12613456023 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.impl.nio; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import org.apache.http.HttpEntity; import org.apache.http.HttpVersion; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.nio.codecs.ChunkDecoder; import org.apache.http.impl.nio.codecs.ChunkEncoder; import org.apache.http.impl.nio.codecs.IdentityDecoder; import org.apache.http.impl.nio.codecs.IdentityEncoder; import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder; import org.apache.http.impl.nio.codecs.LengthDelimitedEncoder; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.protocol.HTTP; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class TestNHttpConnectionBase { @Mock private IOSession session; @Mock private ByteChannel channel; private NHttpConnectionBase conn; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); conn = new NHttpConnectionBase(session, 1024, 1024, HeapByteBufferAllocator.INSTANCE, null, null, LaxContentLengthStrategy.INSTANCE, StrictContentLengthStrategy.INSTANCE); } @Test public void testBasics() throws Exception { Assert.assertEquals("[Not bound]", conn.toString()); Mockito.verify(session).setBufferStatus(conn); } @Test public void testSessionBind() throws Exception { final InetSocketAddress local = new InetSocketAddress( InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 8888); final InetSocketAddress remote = new InetSocketAddress( InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), 80); Mockito.when(session.getLocalAddress()).thenReturn(local); Mockito.when(session.getRemoteAddress()).thenReturn(remote); Mockito.when(session.isClosed()).thenReturn(Boolean.FALSE); conn.bind(session); Mockito.verify(session, Mockito.times(2)).setBufferStatus(conn); 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 testClose() throws Exception { final InetSocketAddress local = new InetSocketAddress( InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 8888); final InetSocketAddress remote = new InetSocketAddress( InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), 80); Mockito.when(session.getLocalAddress()).thenReturn(local); Mockito.when(session.getRemoteAddress()).thenReturn(remote); Mockito.when(session.isClosed()).thenReturn(Boolean.FALSE); conn.close(); Assert.assertEquals(NHttpConnection.CLOSED, conn.getStatus()); Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString()); Mockito.verify(session).close(); } @Test public void testCloseWithBufferedData() throws Exception { final InetSocketAddress local = new InetSocketAddress( InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 8888); final InetSocketAddress remote = new InetSocketAddress( InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), 80); Mockito.when(session.getLocalAddress()).thenReturn(local); Mockito.when(session.getRemoteAddress()).thenReturn(remote); Mockito.when(session.isClosed()).thenReturn(Boolean.FALSE); conn.outbuf.writeLine("stuff"); conn.close(); Assert.assertEquals(NHttpConnection.CLOSING, conn.getStatus()); conn.close(); Assert.assertEquals(NHttpConnection.CLOSING, conn.getStatus()); Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString()); Mockito.verify(session).setEvent(SelectionKey.OP_WRITE); Mockito.verify(session, Mockito.never()).close(); } @Test public void testShutdown() throws Exception { final InetSocketAddress local = new InetSocketAddress( InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 8888); final InetSocketAddress remote = new InetSocketAddress( InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), 80); Mockito.when(session.getLocalAddress()).thenReturn(local); Mockito.when(session.getRemoteAddress()).thenReturn(remote); Mockito.when(session.isClosed()).thenReturn(Boolean.FALSE); conn.outbuf.writeLine("stuff"); conn.shutdown(); Assert.assertEquals(NHttpConnection.CLOSED, conn.getStatus()); Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString()); Mockito.verify(session).shutdown(); } @Test public void testContextOperations() throws Exception { conn.getContext().getAttribute("stuff"); conn.getContext().setAttribute("stuff", "blah"); conn.getContext().removeAttribute("other stuff"); Mockito.verify(session).getAttribute("stuff"); Mockito.verify(session).setAttribute("stuff", "blah"); Mockito.verify(session).removeAttribute("other stuff"); } @Test public void testIOOperations() throws Exception { conn.suspendInput(); Mockito.verify(session).clearEvent(SelectionKey.OP_READ); conn.suspendOutput(); Mockito.verify(session).clearEvent(SelectionKey.OP_WRITE); conn.requestInput(); Mockito.verify(session).setEvent(SelectionKey.OP_READ); conn.requestOutput(); Mockito.verify(session).setEvent(SelectionKey.OP_WRITE); } @Test public void testSocketTimeout() throws Exception { conn.getSocketTimeout(); Mockito.verify(session).getSocketTimeout(); conn.setSocketTimeout(123); Mockito.verify(session).setSocketTimeout(123); } @Test public void testPrepareIdentityDecoder() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(session.channel()).thenReturn(channel); final HttpEntity entity = conn.prepareDecoder(response); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); Assert.assertTrue(conn.contentDecoder instanceof IdentityDecoder); } @Test public void testPrepareLengthDelimitedDecoder() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader(HTTP.CONTENT_LEN, "10"); response.addHeader(HTTP.CONTENT_TYPE, "stuff"); response.addHeader(HTTP.CONTENT_ENCODING, "identity"); Mockito.when(session.channel()).thenReturn(channel); final HttpEntity entity = conn.prepareDecoder(response); Assert.assertNotNull(entity); Assert.assertEquals(10, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); Assert.assertNotNull(entity.getContentType()); Assert.assertEquals("stuff", entity.getContentType().getValue()); Assert.assertNotNull(entity.getContentEncoding()); Assert.assertEquals("identity", entity.getContentEncoding().getValue()); Assert.assertTrue(conn.contentDecoder instanceof LengthDelimitedDecoder); } @Test public void testPrepareChunkDecoder() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader(HTTP.TRANSFER_ENCODING, "chunked"); response.addHeader(HTTP.CONTENT_TYPE, "stuff"); response.addHeader(HTTP.CONTENT_ENCODING, "identity"); Mockito.when(session.channel()).thenReturn(channel); final HttpEntity entity = conn.prepareDecoder(response); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertTrue(entity.isChunked()); Assert.assertNotNull(entity.getContentType()); Assert.assertEquals("stuff", entity.getContentType().getValue()); Assert.assertNotNull(entity.getContentEncoding()); Assert.assertEquals("identity", entity.getContentEncoding().getValue()); Assert.assertTrue(conn.contentDecoder instanceof ChunkDecoder); } @Test public void testPrepareIdentityEncoder() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(session.channel()).thenReturn(channel); conn.prepareEncoder(response); Assert.assertTrue(conn.contentEncoder instanceof IdentityEncoder); } @Test public void testPrepareLengthDelimitedEncoder() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader(HTTP.CONTENT_LEN, "10"); Mockito.when(session.channel()).thenReturn(channel); conn.prepareEncoder(response); Assert.assertTrue(conn.contentEncoder instanceof LengthDelimitedEncoder); } @Test public void testPrepareChunkEncoder() throws Exception { final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader(HTTP.TRANSFER_ENCODING, "chunked"); Mockito.when(session.channel()).thenReturn(channel); conn.prepareEncoder(response); Assert.assertTrue(conn.contentEncoder instanceof ChunkEncoder); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/0040755 0000000 0000000 00000000000 12613456023 027351 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000160 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestHttpMessageParser.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestHttpMessage0100644 0000000 0000000 00000040323 12613456023 032357 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import org.apache.http.Consts; import org.apache.http.HttpException; 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.impl.nio.reactor.SessionInputBufferImpl; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.reactor.SessionInputBuffer; import org.junit.Assert; import org.junit.Test; /** * Simple tests for {@link AbstractMessageParser}. */ public class TestHttpMessageParser { private static ReadableByteChannel newChannel(final String s, final Charset charset) throws UnsupportedEncodingException { return Channels.newChannel(new ByteArrayInputStream(s.getBytes(charset))); } private static ReadableByteChannel newChannel(final String s) throws UnsupportedEncodingException { return newChannel(s, Consts.ASCII); } @Test public void testSimpleParsing() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); requestParser.fillBuffer(newChannel("GET /whatever HTTP/1.1\r\nSome header: stuff\r\n\r\n")); final HttpRequest request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals("/whatever", request.getRequestLine().getUri()); Assert.assertEquals(1, request.getAllHeaders().length); } @Test public void testParsingChunkedMessages() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); requestParser.fillBuffer(newChannel("GET /whatev")); HttpRequest request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("er HTTP/1.1\r")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("\nSome header: stuff\r\n\r\n")); request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals("/whatever", request.getRequestLine().getUri()); Assert.assertEquals(1, request.getAllHeaders().length); } @Test public void testParsingFoldedHeaders() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); requestParser.fillBuffer(newChannel("GET /whatev")); HttpRequest request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("er HTTP/1.1\r")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("\nSome header: stuff\r\n")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel(" more\r\n")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("\tstuff\r\n")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("\r\n")); request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals("/whatever", request.getRequestLine().getUri()); Assert.assertEquals(1, request.getAllHeaders().length); Assert.assertEquals("stuff more stuff", request.getFirstHeader("Some header").getValue()); } @Test public void testParsingBadlyFoldedFirstHeader() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); requestParser.fillBuffer(newChannel("GET /whatev")); HttpRequest request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("er HTTP/1.1\r")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("\n Some header: stuff\r\n")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel(" more stuff\r\n")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("\r\n")); request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals("/whatever", request.getRequestLine().getUri()); Assert.assertEquals(1, request.getAllHeaders().length); Assert.assertEquals("stuff more stuff", request.getFirstHeader("Some header").getValue()); } @Test public void testParsingEmptyFoldedHeader() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); requestParser.fillBuffer(newChannel("GET /whatev")); HttpRequest request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("er HTTP/1.1\r")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("\n Some header: stuff\r\n")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel(" \r\n")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel(" more stuff\r\n")); request = requestParser.parse(); Assert.assertNull(request); requestParser.fillBuffer(newChannel("\r\n")); request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals("/whatever", request.getRequestLine().getUri()); Assert.assertEquals(1, request.getAllHeaders().length); Assert.assertEquals("stuff more stuff", request.getFirstHeader("Some header").getValue()); } @Test public void testParsingIncompleteRequestLine() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); final ReadableByteChannel channel = newChannel("GET /whatever HTTP/1.0"); requestParser.fillBuffer(channel); requestParser.fillBuffer(channel); final HttpRequest request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals(HttpVersion.HTTP_1_0, request.getRequestLine().getProtocolVersion()); } @Test public void testParsingIncompleteHeader() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); final ReadableByteChannel channel = newChannel("GET /whatever HTTP/1.0\r\nHeader: whatever"); requestParser.fillBuffer(channel); requestParser.fillBuffer(channel); final HttpRequest request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals(1, request.getAllHeaders().length); Assert.assertEquals("whatever", request.getFirstHeader("Header").getValue()); } @Test public void testParsingInvalidRequestLine() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); final ReadableByteChannel channel = newChannel("GET garbage\r\n"); requestParser.fillBuffer(channel); try { requestParser.parse(); Assert.fail("HttpException should have been thrown"); } catch (final HttpException ex) { // expected } } @Test public void testParsingInvalidStatusLine() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser responseParser = new DefaultHttpResponseParser(inbuf); final ReadableByteChannel channel = newChannel("HTTP 200 OK\r\n"); responseParser.fillBuffer(channel); try { responseParser.parse(); Assert.fail("HttpException should have been thrown"); } catch (final HttpException ex) { // expected } } @Test public void testParsingInvalidHeader() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser responseParser = new DefaultHttpResponseParser(inbuf); final ReadableByteChannel channel = newChannel("HTTP/1.0 200 OK\r\nstuff\r\n\r\n"); responseParser.fillBuffer(channel); try { responseParser.parse(); Assert.fail("HttpException should have been thrown"); } catch (final HttpException ex) { // expected } } @Test public void testResetParser() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf); ReadableByteChannel channel = newChannel("GET /whatever HTTP/1.0\r\nHeader: one\r\n\r\n"); requestParser.fillBuffer(channel); HttpRequest request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals(1, request.getAllHeaders().length); Assert.assertEquals("one", request.getFirstHeader("Header").getValue()); requestParser.reset(); channel = newChannel("GET /whatever HTTP/1.0\r\nHeader: two\r\n\r\n"); requestParser.fillBuffer(channel); request = requestParser.parse(); Assert.assertNotNull(request); Assert.assertEquals(1, request.getAllHeaders().length); Assert.assertEquals("two", request.getFirstHeader("Header").getValue()); } @Test public void testInvalidConstructor() { try { new DefaultHttpRequestParser(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } } @Test public void testLineLimitForStatus() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf, MessageConstraints.lineLen(0)); requestParser.fillBuffer(newChannel("GET /whatever HTTP/1.0\r\nHeader: one\r\n\r\n")); requestParser.parse(); requestParser.reset(); requestParser = new DefaultHttpRequestParser(inbuf, MessageConstraints.lineLen(15)); try { requestParser.fillBuffer(newChannel("GET /loooooooooooooooong HTTP/1.0\r\nHeader: one\r\n\r\n")); requestParser.parse(); Assert.fail("IOException should have been thrown"); } catch (final IOException expected) { } } @Test public void testLineLimitForHeader() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf, MessageConstraints.lineLen(0)); requestParser.fillBuffer(newChannel("GET /whatever HTTP/1.0\r\nHeader: one\r\n\r\n")); requestParser.parse(); requestParser.reset(); requestParser = new DefaultHttpRequestParser(inbuf, MessageConstraints.lineLen(15)); requestParser.fillBuffer(newChannel("GET / HTTP/1.0\r\nHeader: 9012345\r\n\r\n")); requestParser.parse(); requestParser.reset(); try { requestParser.fillBuffer(newChannel("GET / HTTP/1.0\r\nHeader: 90123456\r\n\r\n")); requestParser.parse(); Assert.fail("IOException should have been thrown"); } catch (final IOException expected) { } } @Test public void testLineLimitForFoldedHeader() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final MessageConstraints constraints = MessageConstraints.custom() .setMaxHeaderCount(2).setMaxLineLength(15).build(); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf, constraints); try { requestParser.fillBuffer(newChannel("GET / HTTP/1.0\r\nHeader: 9012345\r\n" + " 23456789012345\r\n 23456789012345\r\n 23456789012345\r\n\r\n")); requestParser.parse(); Assert.fail("IOException should have been thrown"); } catch (final IOException expected) { } } @Test public void testMaxHeaderCount() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, Consts.ASCII); final MessageConstraints constraints = MessageConstraints.custom() .setMaxHeaderCount(2).setMaxLineLength(-1).build(); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf, constraints); requestParser.fillBuffer(newChannel("GET /whatever HTTP/1.0\r\nHeader: one\r\nHeader: two\r\n\r\n")); requestParser.parse(); requestParser.reset(); try { requestParser.fillBuffer(newChannel("GET /whatever HTTP/1.0\r\nHeader: one\r\n" + "Header: two\r\nHeader: three\r\n\r\n")); requestParser.parse(); Assert.fail("IOException should have been thrown"); } catch (final IOException expected) { } } @Test public void testDetectLineLimitEarly() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(2, 128, Consts.ASCII); final NHttpMessageParser requestParser = new DefaultHttpRequestParser(inbuf, MessageConstraints.lineLen(2)); final ReadableByteChannel channel = newChannel("GET / HTTP/1.0\r\nHeader: one\r\n\r\n"); Assert.assertEquals(2, requestParser.fillBuffer(channel)); Assert.assertNull(requestParser.parse()); Assert.assertEquals(4, requestParser.fillBuffer(channel)); try { requestParser.parse(); Assert.fail("IOException should have been thrown"); } catch (final IOException expected) { } } } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestChunkDecoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestChunkDecode0100644 0000000 0000000 00000061417 12613456023 032316 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import org.apache.http.ConnectionClosedException; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.MalformedChunkCodingException; import org.apache.http.MessageConstraintException; import org.apache.http.ReadableByteChannelMock; import org.apache.http.TruncatedChunkException; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.reactor.SessionInputBufferImpl; import org.apache.http.nio.reactor.SessionInputBuffer; import org.junit.Assert; import org.junit.Test; /** * Simple tests for {@link ChunkDecoder}. */ public class TestChunkDecoder { @Test public void testBasicDecoding() throws Exception { final String s = "5\r\n01234\r\n5\r\n56789\r\n6\r\nabcdef\r\n0\r\n\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(16, bytesRead); Assert.assertEquals("0123456789abcdef", CodecTestUtils.convert(dst)); final Header[] footers = decoder.getFooters(); Assert.assertEquals(0, footers.length); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals("[chunk-coded; completed: true]", decoder.toString()); } @Test public void testComplexDecoding() throws Exception { final String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { final int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", CodecTestUtils.convert(dst)); final Header[] footers = decoder.getFooters(); 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()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); } @Test public void testDecodingWithSmallBuffer() throws Exception { final String s1 = "5\r\n01234\r\n5\r\n5678"; final String s2 = "9\r\n6\r\nabcdef\r\n0\r\n\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s1, s2}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); final ByteBuffer tmp = ByteBuffer.allocate(4); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { final int i = decoder.read(tmp); if (i > 0) { bytesRead += i; } tmp.flip(); dst.put(tmp); tmp.compact(); } Assert.assertEquals(16, bytesRead); Assert.assertEquals("0123456789abcdef", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); } @Test public void testMalformedChunk() throws Exception { final String s = "5\r\n01234----------------------------------------------------------" + "-----------------------------------------------------------------------------" + "-----------------------------------------------------------------------------"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(32, 32, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (final MalformedChunkCodingException ex) { // expected } } @Test public void testIncompleteChunkDecoding() throws Exception { final String[] chunks = { "10;", "key=\"value\"\r", "\n123456789012345", "6\r\n5\r\n12", "345\r\n6\r", "\nabcdef\r", "\n0\r\nFoot", "er1: abcde\r\nFooter2: f", "ghij\r\n\r\n" }; final ReadableByteChannel channel = new ReadableByteChannelMock( chunks, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ByteBuffer dst = ByteBuffer.allocate(1024); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { final int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(27, bytesRead); Assert.assertEquals("123456789012345612345abcdef", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); final Header[] footers = decoder.getFooters(); 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()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); } @Test(expected=MalformedChunkCodingException.class) public void testMalformedChunkSizeDecoding() throws Exception { final String s = "5\r\n01234\r\n5zz\r\n56789\r\n6\r\nabcdef\r\n0\r\n\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); decoder.read(dst); } @Test(expected=MalformedChunkCodingException.class) public void testMalformedChunkEndingDecoding() throws Exception { final String s = "5\r\n01234\r\n5\r\n56789\r\r6\r\nabcdef\r\n0\r\n\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); decoder.read(dst); } @Test(expected=TruncatedChunkException.class) public void testMalformedChunkTruncatedChunk() throws Exception { final String s = "3\r\n12"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); Assert.assertEquals(2, decoder.read(dst)); decoder.read(dst); } @Test public void testFoldedFooters() throws Exception { final String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\n \r\n fghij\r\n\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); final int bytesRead = decoder.read(dst); Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", CodecTestUtils.convert(dst)); final Header[] footers = decoder.getFooters(); Assert.assertEquals(1, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde fghij", footers[0].getValue()); } @Test(expected=IOException.class) public void testMalformedFooters() throws Exception { final String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1 abcde\r\n\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); decoder.read(dst); } @Test(expected=MalformedChunkCodingException.class) public void testMissingLastCRLF() throws Exception { final String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); while (dst.hasRemaining() && !decoder.isCompleted()) { decoder.read(dst); } } @Test(expected=ConnectionClosedException.class) public void testMissingClosingChunk() throws Exception { final String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); long bytesRead = 0; try { while (dst.hasRemaining() && !decoder.isCompleted()) { final int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } } catch (final MalformedChunkCodingException ex) { Assert.assertEquals(26L, bytesRead); Assert.assertEquals("12345678901234561234512345", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); throw ex; } } @Test public void testReadingWitSmallBuffer() throws Exception { final String s = "10\r\n1234567890123456\r\n" + "40\r\n12345678901234561234567890123456" + "12345678901234561234567890123456\r\n0\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); final ByteBuffer tmp = ByteBuffer.allocate(10); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { final int i = decoder.read(tmp); if (i > 0) { bytesRead += i; tmp.flip(); dst.put(tmp); tmp.compact(); } } Assert.assertEquals(80, bytesRead); Assert.assertEquals("12345678901234561234567890123456" + "12345678901234561234567890123456" + "1234567890123456", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); } @Test public void testEndOfStreamConditionReadingFooters() throws Exception { final String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { final int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); } @Test public void testTooLongChunkHeader() throws Exception { final String s = "5; and some very looooong comment\r\n12345\r\n0\r\n"; final ReadableByteChannel channel1 = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf1 = new SessionInputBufferImpl(1024, 256, MessageConstraints.DEFAULT, null, null); final HttpTransportMetricsImpl metrics1 = new HttpTransportMetricsImpl(); final ChunkDecoder decoder1 = new ChunkDecoder(channel1, inbuf1, metrics1); final ByteBuffer dst = ByteBuffer.allocate(1024); while (dst.hasRemaining() && !decoder1.isCompleted()) { decoder1.read(dst); } Assert.assertEquals("12345", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder1.isCompleted()); final ReadableByteChannel channel2 = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf2 = new SessionInputBufferImpl(1024, 256, MessageConstraints.lineLen(10), null, null); final HttpTransportMetricsImpl metrics2 = new HttpTransportMetricsImpl(); final ChunkDecoder decoder2 = new ChunkDecoder(channel2, inbuf2, metrics2); dst.clear(); try { decoder2.read(dst); Assert.fail("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } } @Test public void testTooLongFooter() throws Exception { final String s = "10\r\n1234567890123456\r\n" + "0\r\nFooter1: looooooooooooooooooooooooooooooooooooooooooooooooooooooog\r\n\r\n"; // final String s = "10\r\n1234567890123456\r\n" + // "0\r\nFooter1: looooooooooooooooooooooooooooooooooooooooog\r\n \r\n fghij\r\n\r\n"; final ReadableByteChannel channel1 = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf1 = new SessionInputBufferImpl(1024, 256, MessageConstraints.DEFAULT, Consts.ASCII); final HttpTransportMetricsImpl metrics1 = new HttpTransportMetricsImpl(); final ChunkDecoder decoder1 = new ChunkDecoder(channel1, inbuf1, metrics1); final ByteBuffer dst = ByteBuffer.allocate(1024); final int bytesRead = decoder1.read(dst); Assert.assertEquals(16, bytesRead); Assert.assertEquals("1234567890123456", CodecTestUtils.convert(dst)); final Header[] footers = decoder1.getFooters(); Assert.assertNotNull(footers); Assert.assertEquals(1, footers.length); final ReadableByteChannel channel2 = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf2 = new SessionInputBufferImpl(1024, 256, MessageConstraints.lineLen(25), Consts.ASCII); final HttpTransportMetricsImpl metrics2 = new HttpTransportMetricsImpl(); final ChunkDecoder decoder2 = new ChunkDecoder(channel2, inbuf2, metrics2); dst.clear(); try { decoder2.read(dst); Assert.fail("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } } @Test public void testTooLongFoldedFooter() throws Exception { final String s = "10\r\n1234567890123456\r\n" + "0\r\nFooter1: blah\r\n blah\r\n blah\r\n blah\r\n blah\r\n blah\r\n blah\r\n blah\r\n\r\n"; final ReadableByteChannel channel1 = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf1 = new SessionInputBufferImpl(1024, 256, MessageConstraints.DEFAULT, Consts.ASCII); final HttpTransportMetricsImpl metrics1 = new HttpTransportMetricsImpl(); final ChunkDecoder decoder1 = new ChunkDecoder(channel1, inbuf1, metrics1); final ByteBuffer dst = ByteBuffer.allocate(1024); final int bytesRead = decoder1.read(dst); Assert.assertEquals(16, bytesRead); Assert.assertEquals("1234567890123456", CodecTestUtils.convert(dst)); final Header[] footers = decoder1.getFooters(); Assert.assertNotNull(footers); Assert.assertEquals(1, footers.length); final MessageConstraints constraints = MessageConstraints.lineLen(25); final ReadableByteChannel channel2 = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf2 = new SessionInputBufferImpl(1024, 256, constraints, Consts.ASCII); final HttpTransportMetricsImpl metrics2 = new HttpTransportMetricsImpl(); final ChunkDecoder decoder2 = new ChunkDecoder(channel2, inbuf2, constraints, metrics2); dst.clear(); try { decoder2.read(dst); Assert.fail("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } } @Test public void testTooManyFooters() throws Exception { final String s = "10\r\n1234567890123456\r\n" + "0\r\nFooter1: blah\r\nFooter2: blah\r\nFooter3: blah\r\nFooter4: blah\r\n\r\n"; final ReadableByteChannel channel1 = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf1 = new SessionInputBufferImpl(1024, 256, MessageConstraints.DEFAULT, Consts.ASCII); final HttpTransportMetricsImpl metrics1 = new HttpTransportMetricsImpl(); final ChunkDecoder decoder1 = new ChunkDecoder(channel1, inbuf1, metrics1); final ByteBuffer dst = ByteBuffer.allocate(1024); final int bytesRead = decoder1.read(dst); Assert.assertEquals(16, bytesRead); Assert.assertEquals("1234567890123456", CodecTestUtils.convert(dst)); final Header[] footers = decoder1.getFooters(); Assert.assertNotNull(footers); Assert.assertEquals(4, footers.length); final MessageConstraints constraints = MessageConstraints.custom() .setMaxHeaderCount(3).build(); final ReadableByteChannel channel2 = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf2 = new SessionInputBufferImpl(1024, 256, constraints, Consts.ASCII); final HttpTransportMetricsImpl metrics2 = new HttpTransportMetricsImpl(); final ChunkDecoder decoder2 = new ChunkDecoder(channel2, inbuf2, constraints, metrics2); dst.clear(); try { decoder2.read(dst); Assert.fail("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } } @Test public void testInvalidConstructor() { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); try { new ChunkDecoder(null, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new ChunkDecoder(channel, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new ChunkDecoder(channel, inbuf, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } } @Test(expected=IllegalArgumentException.class) public void testInvalidInput() throws Exception { final String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1 abcde\r\n\r\n"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); decoder.read(null); } } ././@LongLink0100644 0000000 0000000 00000000165 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestLengthDelimitedDecoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestLengthDelim0100644 0000000 0000000 00000052350 12613456023 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.impl.nio.codecs; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import org.apache.http.ConnectionClosedException; import org.apache.http.Consts; import org.apache.http.ReadableByteChannelMock; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.reactor.SessionInputBufferImpl; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.util.EncodingUtils; import org.junit.After; import org.junit.Assert; import org.junit.Test; /** * Simple tests for {@link LengthDelimitedDecoder}. */ public class TestLengthDelimitedDecoder { private File tmpfile; protected File createTempFile() throws IOException { this.tmpfile = File.createTempFile("testFile", ".txt"); return this.tmpfile; } @After public void deleteTempFile() { if (this.tmpfile != null && this.tmpfile.exists()) { this.tmpfile.delete(); } } @Test public void testBasicDecoding() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(6, bytesRead); Assert.assertEquals("stuff;", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(6, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(10, bytesRead); Assert.assertEquals("more stuff", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); Assert.assertEquals("[content length: 16; pos: 16; completed: true]", decoder.toString()); } @Test public void testCodingBeyondContentLimit() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] { "stuff;", "more stuff; and a lot more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(6, bytesRead); Assert.assertEquals("stuff;", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(6, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(10, bytesRead); Assert.assertEquals("more stuff", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); } @Test public void testBasicDecodingSmallBuffer() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); final ByteBuffer dst = ByteBuffer.allocate(4); int bytesRead = decoder.read(dst); Assert.assertEquals(4, bytesRead); Assert.assertEquals("stuf", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(4, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(2, bytesRead); Assert.assertEquals("f;", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(6, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(4, bytesRead); Assert.assertEquals("more", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(10, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(4, bytesRead); Assert.assertEquals(" stu", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(14, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(2, bytesRead); Assert.assertEquals("ff", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); } @Test public void testDecodingFromSessionBuffer1() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); inbuf.fill(channel); Assert.assertEquals(6, inbuf.length()); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(6, bytesRead); Assert.assertEquals("stuff;", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(10, bytesRead); Assert.assertEquals("more stuff", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(10, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(10, metrics.getBytesTransferred()); } @Test public void testDecodingFromSessionBuffer2() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] { "stuff;", "more stuff; and a lot more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); inbuf.fill(channel); inbuf.fill(channel); Assert.assertEquals(38, inbuf.length()); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(16, bytesRead); Assert.assertEquals("stuff;more stuff", CodecTestUtils.convert(dst)); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); } /* ----------------- FileChannel Part testing --------------------------- */ @Test public void testBasicDecodingFile() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 36); createTempFile(); final RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { final long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } } finally { testfile.close(); } Assert.assertEquals(this.tmpfile.length(), metrics.getBytesTransferred()); Assert.assertEquals("stuff; more stuff; a lot more stuff!", CodecTestUtils.readFromFile(this.tmpfile)); } @Test public void testDecodingFileWithBufferedSessionData() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 36); final int i = inbuf.fill(channel); Assert.assertEquals(7, i); createTempFile(); final RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { final long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } } finally { testfile.close(); } Assert.assertEquals(this.tmpfile.length() - 7, metrics.getBytesTransferred()); Assert.assertEquals("stuff; more stuff; a lot more stuff!", CodecTestUtils.readFromFile(this.tmpfile)); } @Test public void testDecodingFileWithOffsetAndBufferedSessionData() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 36); final int i = inbuf.fill(channel); Assert.assertEquals(7, i); final byte[] beginning = EncodingUtils.getAsciiBytes("beginning; "); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write(beginning); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); long pos = beginning.length; while (!decoder.isCompleted()) { if(testfile.length() < pos) { testfile.setLength(pos); } final long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } } finally { testfile.close(); } // count everything except the initial 7 bytes that went to the session buffer Assert.assertEquals(this.tmpfile.length() - 7 - beginning.length, metrics.getBytesTransferred()); Assert.assertEquals("beginning; stuff; more stuff; a lot more stuff!", CodecTestUtils.readFromFile(this.tmpfile)); } @Test public void testWriteBeyondFileSize() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"a"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); createTempFile(); final RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("IOException should have been thrown"); } catch(final IOException expected) { } } finally { testfile.close(); } } @Test public void testCodingBeyondContentLimitFile() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] { "stuff;", "more stuff; and a lot more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); createTempFile(); final RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); long bytesRead = decoder.transfer(fchannel, 0, 6); Assert.assertEquals(6, bytesRead); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(6, metrics.getBytesTransferred()); bytesRead = decoder.transfer(fchannel,0 , 10); Assert.assertEquals(10, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); bytesRead = decoder.transfer(fchannel, 0, 1); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); } finally { testfile.close(); } } @Test public void testInvalidConstructor() { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); try { new LengthDelimitedDecoder(null, null, null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new LengthDelimitedDecoder(channel, null, null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new LengthDelimitedDecoder(channel, inbuf, null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new LengthDelimitedDecoder(channel, inbuf, metrics, -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } } @Test public void testInvalidInput() throws Exception { final String s = "stuff"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 3); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testZeroLengthDecoding() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 0); final ByteBuffer dst = ByteBuffer.allocate(1024); final int bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); } @Test(expected=ConnectionClosedException.class) public void testTruncatedContent() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"1234567890"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 20); final ByteBuffer dst = ByteBuffer.allocate(1024); final int bytesRead = decoder.read(dst); Assert.assertEquals(10, bytesRead); decoder.read(dst); } @Test(expected=ConnectionClosedException.class) public void testTruncatedContentWithFile() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"1234567890"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 20); createTempFile(); final RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); final long bytesRead = decoder.transfer(fchannel, 0, Integer.MAX_VALUE); Assert.assertEquals(10, bytesRead); decoder.transfer(fchannel, 0, Integer.MAX_VALUE); } finally { testfile.close(); } } } ././@LongLink0100644 0000000 0000000 00000000165 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestLengthDelimitedEncoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestLengthDelim0100644 0000000 0000000 00000067157 12613456023 032345 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import org.apache.http.Consts; import org.apache.http.WritableByteChannelMock; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.reactor.SessionOutputBufferImpl; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * Simple tests for {@link LengthDelimitedEncoder}. */ public class TestLengthDelimitedEncoder { private File tmpfile; protected File createTempFile() throws IOException { this.tmpfile = File.createTempFile("testFile", ".txt"); return this.tmpfile; } @After public void deleteTempFile() { if (this.tmpfile != null && this.tmpfile.exists()) { this.tmpfile.delete(); } } @Test public void testBasicCoding() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 16); encoder.write(CodecTestUtils.wrap("stuff;")); encoder.write(CodecTestUtils.wrap("more stuff")); final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); Assert.assertEquals("[content length: 16; pos: 16; completed: true]", encoder.toString()); } @Test public void testCodingBeyondContentLimit() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 16); encoder.write(CodecTestUtils.wrap("stuff;")); encoder.write(CodecTestUtils.wrap("more stuff; and a lot more stuff")); final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); } @Test public void testCodingEmptyBuffer() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 16); encoder.write(CodecTestUtils.wrap("stuff;")); final ByteBuffer empty = ByteBuffer.allocate(100); empty.flip(); encoder.write(empty); encoder.write(null); encoder.write(CodecTestUtils.wrap("more stuff")); final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); } @Test public void testCodingCompleted() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 5); encoder.write(CodecTestUtils.wrap("stuff")); try { encoder.write(CodecTestUtils.wrap("more stuff")); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException ex) { // ignore } } @Test public void testInvalidConstructor() { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); try { new LengthDelimitedEncoder(null, null, null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new LengthDelimitedEncoder(channel, null, null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new LengthDelimitedEncoder(channel, outbuf, null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new LengthDelimitedEncoder(channel, outbuf, metrics, -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } } @Test public void testCodingBeyondContentLimitFromFile() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 16); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("stuff;".getBytes(Consts.ASCII)); testfile.write("more stuff; and a lot more stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); } @Test public void testCodingEmptyFile() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 16); encoder.write(CodecTestUtils.wrap("stuff;")); //Create an empty file createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); testfile.close(); testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); encoder.write(CodecTestUtils.wrap("more stuff")); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); } @Test public void testCodingCompletedFromFile() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 5); encoder.write(CodecTestUtils.wrap("stuff")); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("more stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 10); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException ex) { // ignore } finally { testfile.close(); } } @Test public void testCodingFromFileSmaller() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 16); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("stuff;".getBytes(Consts.ASCII)); testfile.write("more stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); } @Test public void testCodingFromFileFlushBuffer() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 16); outbuf.writeLine("header"); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("stuff;".getBytes(Consts.ASCII)); testfile.write("more stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("header\r\nstuff;more stuff", s); } @Test public void testCodingFromFileChannelSaturated() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64, 4); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 16); outbuf.writeLine("header"); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); encoder.transfer(fchannel, 0, 20); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertFalse(encoder.isCompleted()); Assert.assertEquals("head", s); } @Test public void testCodingNoFragmentBuffering() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); outbuf.writeLine("header"); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 0); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Mockito.verify(channel, Mockito.times(2)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(13, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("header\r\nstuff", s); } @Test public void testCodingFragmentBuffering() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); outbuf.writeLine("header"); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 32); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Mockito.verify(channel, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).flush(channel); Assert.assertEquals(0, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("header\r\nstuff", s); } @Test public void testCodingFragmentBufferingMultipleFragments() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 32); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).flush(channel); Assert.assertEquals(0, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff-more stuff", s); } @Test public void testCodingFragmentBufferingMultipleFragmentsBeyondContentLimit() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16, 32); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff; and a lot more stuff"))); Mockito.verify(channel, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).flush(channel); Assert.assertEquals(0, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff-more stuff", s); } @Test public void testCodingFragmentBufferingLargeFragment() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); outbuf.writeLine("header"); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 2); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Mockito.verify(channel, Mockito.times(2)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(13, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("header\r\nstuff", s); } @Test public void testCodingFragmentBufferingTinyFragments() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 1); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.times(5)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).flush(channel); Assert.assertEquals(18, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff---more stuff", s); } @Test public void testCodingFragmentBufferingTinyFragments2() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 2); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.times(4)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(2)).flush(channel); Assert.assertEquals(18, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff---more stuff", s); } @Test public void testCodingFragmentBufferingTinyFragments3() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 3); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(2, encoder.write(CodecTestUtils.wrap("--"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.times(4)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(5)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(2)).flush(channel); Assert.assertEquals(21, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff------more stuff", s); } @Test public void testCodingFragmentBufferingBufferFlush() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 8); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(6, encoder.write(CodecTestUtils.wrap("-stuff"))); Mockito.verify(channel, Mockito.times(1)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(8, metrics.getBytesTransferred()); Assert.assertEquals(3, outbuf.length()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff-stuff", s); } @Test public void testCodingFragmentBufferingBufferFlush2() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 8); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(16, encoder.write(CodecTestUtils.wrap("-much more stuff"))); Mockito.verify(channel, Mockito.times(2)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(21, metrics.getBytesTransferred()); Assert.assertEquals(0, outbuf.length()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff-much more stuff", s); } @Test public void testCodingFragmentBufferingChannelSaturated() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64, 8)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 3); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(0, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(0, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.times(5)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(6)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(4)).flush(channel); Assert.assertEquals(8, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff---", s); Assert.assertEquals(3, outbuf.length()); } @Test public void testCodingFragmentBufferingChannelSaturated2() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64, 8)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 100, 8); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("much more stuff"))); Mockito.verify(channel, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(8, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff--m", s); Assert.assertEquals(0, outbuf.length()); } } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestIdentityEncoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestIdentityEnc0100644 0000000 0000000 00000057254 12613456023 032365 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import org.apache.http.Consts; import org.apache.http.WritableByteChannelMock; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.reactor.SessionOutputBufferImpl; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * Simple tests for {@link IdentityEncoder}. */ public class TestIdentityEncoder { private File tmpfile; protected File createTempFile() throws IOException { this.tmpfile = File.createTempFile("testFile", ".txt"); return this.tmpfile; } @After public void deleteTempFile() { if (this.tmpfile != null && this.tmpfile.exists()) { this.tmpfile.delete(); } } @Test public void testBasicCoding() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); encoder.complete(); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals(5, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff", s); Assert.assertEquals("[identity; completed: true]", encoder.toString()); } @Test public void testCodingEmptySrcBuffer() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics); encoder.write(CodecTestUtils.wrap("stuff")); final ByteBuffer empty = ByteBuffer.allocate(100); empty.flip(); encoder.write(empty); encoder.write(null); encoder.complete(); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("stuff", s); } @Test public void testCodingCompleted() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics); encoder.write(CodecTestUtils.wrap("stuff")); encoder.complete(); try { encoder.write(CodecTestUtils.wrap("more stuff")); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException ex) { // ignore } } @Test public void testInvalidConstructor() { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); try { new IdentityEncoder(null, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new IdentityEncoder(channel, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new IdentityEncoder(channel, outbuf, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } } @Test public void testCodingFromFile() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("stuff;".getBytes(Consts.ASCII)); testfile.write("more stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertFalse(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); } @Test public void testCodingEmptyFile() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics); encoder.write(CodecTestUtils.wrap("stuff;")); //Create an empty file createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); testfile.close(); testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); encoder.write(CodecTestUtils.wrap("more stuff")); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertFalse(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); } @Test public void testCodingFromFileSmaller() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("stuff;".getBytes(Consts.ASCII)); testfile.write("more stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertFalse(encoder.isCompleted()); Assert.assertEquals("stuff;more stuff", s); } @Test public void testCodingFromFileFlushBuffer() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics); outbuf.writeLine("header"); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("stuff;".getBytes(Consts.ASCII)); testfile.write("more stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertFalse(encoder.isCompleted()); Assert.assertEquals("header\r\nstuff;more stuff", s); } @Test public void testCodingFromFileChannelSaturated() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64, 4); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics); outbuf.writeLine("header"); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write("stuff".getBytes(Consts.ASCII)); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); encoder.transfer(fchannel, 0, 20); encoder.transfer(fchannel, 0, 20); } finally { testfile.close(); } final String s = channel.dump(Consts.ASCII); Assert.assertFalse(encoder.isCompleted()); Assert.assertEquals("head", s); } @Test public void testCodingNoFragmentBuffering() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); outbuf.writeLine("header"); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 0); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Mockito.verify(channel, Mockito.times(2)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(13, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("header\r\nstuff", s); } @Test public void testCodingFragmentBuffering() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); outbuf.writeLine("header"); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 32); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Mockito.verify(channel, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).flush(channel); Assert.assertEquals(0, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("header\r\nstuff", s); } @Test public void testCodingFragmentBufferingMultipleFragments() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 32); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).flush(channel); Assert.assertEquals(0, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff-more stuff", s); } @Test public void testCodingFragmentBufferingLargeFragment() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); outbuf.writeLine("header"); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 2); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Mockito.verify(channel, Mockito.times(2)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.never()).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(13, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("header\r\nstuff", s); } @Test public void testCodingFragmentBufferingTinyFragments() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 1); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.times(5)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).flush(channel); Assert.assertEquals(18, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff---more stuff", s); } @Test public void testCodingFragmentBufferingTinyFragments2() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 2); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.times(4)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(2)).flush(channel); Assert.assertEquals(18, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff---more stuff", s); } @Test public void testCodingFragmentBufferingTinyFragments3() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 3); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(2, encoder.write(CodecTestUtils.wrap("--"))); Assert.assertEquals(10, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.times(4)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(5)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(2)).flush(channel); Assert.assertEquals(21, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff------more stuff", s); } @Test public void testCodingFragmentBufferingBufferFlush() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 8); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(6, encoder.write(CodecTestUtils.wrap("-stuff"))); Mockito.verify(channel, Mockito.times(1)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(8, metrics.getBytesTransferred()); Assert.assertEquals(3, outbuf.length()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff-stuff", s); } @Test public void testCodingFragmentBufferingBufferFlush2() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 8); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(16, encoder.write(CodecTestUtils.wrap("-much more stuff"))); Mockito.verify(channel, Mockito.times(2)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(21, metrics.getBytesTransferred()); Assert.assertEquals(0, outbuf.length()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff-much more stuff", s); } @Test public void testCodingFragmentBufferingChannelSaturated() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64, 8)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 3); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(0, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(0, encoder.write(CodecTestUtils.wrap("more stuff"))); Mockito.verify(channel, Mockito.times(5)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(6)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(4)).flush(channel); Assert.assertEquals(8, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff---", s); Assert.assertEquals(3, outbuf.length()); } @Test public void testCodingFragmentBufferingChannelSaturated2() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(64, 8)); final SessionOutputBuffer outbuf = Mockito.spy(new SessionOutputBufferImpl(1024, 128)); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityEncoder encoder = new IdentityEncoder(channel, outbuf, metrics, 8); Assert.assertEquals(5, encoder.write(CodecTestUtils.wrap("stuff"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("-"))); Assert.assertEquals(1, encoder.write(CodecTestUtils.wrap("much more stuff"))); Mockito.verify(channel, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(3)).write(Mockito.any()); Mockito.verify(outbuf, Mockito.times(1)).flush(channel); Assert.assertEquals(8, metrics.getBytesTransferred()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("stuff--m", s); Assert.assertEquals(0, outbuf.length()); } } ././@LongLink0100644 0000000 0000000 00000000151 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/CodecTestUtils.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/CodecTestUtils.0100644 0000000 0000000 00000004537 12613456023 032256 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.ByteBuffer; import org.apache.http.util.EncodingUtils; class CodecTestUtils { public static ByteBuffer wrap(final String s) { return ByteBuffer.wrap(EncodingUtils.getAsciiBytes(s)); } public static String convert(final ByteBuffer src) { src.flip(); final StringBuilder buffer = new StringBuilder(src.remaining()); while (src.hasRemaining()) { buffer.append((char)(src.get() & 0xff)); } return buffer.toString(); } public static String readFromFile(final File file) throws Exception { final FileInputStream filestream = new FileInputStream(file); final InputStreamReader reader = new InputStreamReader(filestream); try { final StringBuilder buffer = new StringBuilder(); final char[] tmp = new char[2048]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { reader.close(); } } } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestIdentityDecoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestIdentityDec0100644 0000000 0000000 00000030557 12613456023 032350 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import org.apache.http.Consts; import org.apache.http.ReadableByteChannelMock; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.reactor.SessionInputBufferImpl; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.util.EncodingUtils; import org.junit.After; import org.junit.Assert; import org.junit.Test; /** * Simple tests for {@link LengthDelimitedDecoder}. */ public class TestIdentityDecoder { private File tmpfile; protected File createTempFile() throws IOException { this.tmpfile = File.createTempFile("testFile", ".txt"); return this.tmpfile; } @After public void deleteTempFile() { if (this.tmpfile != null && this.tmpfile.exists()) { this.tmpfile.delete(); } } @Test public void testBasicDecoding() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityDecoder decoder = new IdentityDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(6, bytesRead); Assert.assertEquals("stuff;", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(6, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(10, bytesRead); Assert.assertEquals("more stuff", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(16, metrics.getBytesTransferred()); Assert.assertEquals("[identity; completed: true]", decoder.toString()); } @Test public void testDecodingFromSessionBuffer() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); inbuf.fill(channel); Assert.assertEquals(6, inbuf.length()); final IdentityDecoder decoder = new IdentityDecoder(channel, inbuf, metrics); final ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(6, bytesRead); Assert.assertEquals("stuff;", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); // doesn't count if from session buffer dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(10, bytesRead); Assert.assertEquals("more stuff", CodecTestUtils.convert(dst)); Assert.assertFalse(decoder.isCompleted()); Assert.assertEquals(10, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(10, metrics.getBytesTransferred()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(10, metrics.getBytesTransferred()); } @Test public void testBasicDecodingFile() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); createTempFile(); final RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { final long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); } finally { testfile.close(); } Assert.assertEquals("stuff; more stuff; a lot more stuff!", CodecTestUtils.readFromFile(this.tmpfile)); } @Test public void testDecodingFileWithBufferedSessionData() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); final int i = inbuf.fill(channel); Assert.assertEquals(7, i); createTempFile(); final RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { final long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } // count everything except the initial 7 bytes that went to the session buffer Assert.assertEquals(testfile.length() - 7, metrics.getBytesTransferred()); } finally { testfile.close(); } Assert.assertEquals("stuff; more stuff; a lot more stuff!", CodecTestUtils.readFromFile(this.tmpfile)); } @Test public void testDecodingFileWithOffsetAndBufferedSessionData() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); final int i = inbuf.fill(channel); Assert.assertEquals(7, i); final byte[] beginning = EncodingUtils.getAsciiBytes("beginning; "); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { testfile.write(beginning); } finally { testfile.close(); } testfile = new RandomAccessFile(this.tmpfile, "rw"); try { final FileChannel fchannel = testfile.getChannel(); long pos = beginning.length; while (!decoder.isCompleted()) { if(testfile.length() < pos) { testfile.setLength(pos); } final long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } // count everything except the initial 7 bytes that went to the session buffer Assert.assertEquals(testfile.length() - 7 - beginning.length, metrics.getBytesTransferred()); } finally { testfile.close(); } Assert.assertEquals("beginning; stuff; more stuff; a lot more stuff!", CodecTestUtils.readFromFile(this.tmpfile)); } @Test public void testWriteBeyondFileSize() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"a"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); createTempFile(); final RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { Assert.assertEquals(0, testfile.length()); final FileChannel fchannel = testfile.getChannel(); try { decoder.transfer(fchannel, 5, 10); Assert.fail("expected IOException"); } catch(final IOException iox) {} } finally { testfile.close(); } } @Test public void testInvalidConstructor() { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff;", "more stuff"}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); try { new IdentityDecoder(null, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new IdentityDecoder(channel, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new IdentityDecoder(channel, inbuf, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } } @Test public void testInvalidInput() throws Exception { final String s = "stuff"; final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, Consts.ASCII); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityDecoder decoder = new IdentityDecoder(channel, inbuf, metrics); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } } ././@LongLink0100644 0000000 0000000 00000000153 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestChunkEncoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/codecs/TestChunkEncode0100644 0000000 0000000 00000022030 12613456023 032314 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.nio.ByteBuffer; import org.apache.http.Consts; import org.apache.http.WritableByteChannelMock; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.reactor.SessionOutputBufferImpl; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * Simple tests for {@link ChunkEncoder}. */ public class TestChunkEncoder { @Test public void testBasicCoding() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkEncoder encoder = new ChunkEncoder(channel, outbuf, metrics); encoder.write(CodecTestUtils.wrap("12345")); encoder.write(CodecTestUtils.wrap("678")); encoder.write(CodecTestUtils.wrap("90")); encoder.complete(); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("5\r\n12345\r\n3\r\n678\r\n2\r\n90\r\n0\r\n\r\n", s); Assert.assertEquals("[chunk-coded; completed: true]", encoder.toString()); } @Test public void testChunkNoExceed() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 16); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkEncoder encoder = new ChunkEncoder(channel, outbuf, metrics); encoder.write(CodecTestUtils.wrap("1234")); encoder.complete(); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("4\r\n1234\r\n0\r\n\r\n", s); } @Test // See HTTPCORE-239 public void testLimitedChannel() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(16, 16); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(16, 16); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkEncoder encoder = new ChunkEncoder(channel, outbuf, metrics); // fill up the channel channel.write(CodecTestUtils.wrap("0123456789ABCDEF")); // fill up the out buffer outbuf.write(CodecTestUtils.wrap("0123456789ABCDEF")); final ByteBuffer src = CodecTestUtils.wrap("0123456789ABCDEF"); Assert.assertEquals(0, encoder.write(src)); Assert.assertEquals(0, encoder.write(src)); Assert.assertEquals(0, encoder.write(src)); // should not be able to copy any bytes, until we flush the channel and buffer channel.reset(); outbuf.flush(channel); channel.reset(); Assert.assertEquals(10, encoder.write(src)); channel.flush(); Assert.assertEquals(6, encoder.write(src)); channel.flush(); Assert.assertEquals(0, encoder.write(src)); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("4\r\n0123\r\n4\r\n4567\r\n2\r\n89\r\n4\r\nABCD\r\n2\r\nEF\r\n", s); } @Test public void testBufferFragments() throws Exception { final WritableByteChannelMock channel = Mockito.spy(new WritableByteChannelMock(1024)); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 1024); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkEncoder encoder = new ChunkEncoder(channel, outbuf, metrics, 1024); Assert.assertEquals(16, encoder.write(CodecTestUtils.wrap("0123456789ABCDEF"))); Assert.assertEquals(16, encoder.write(CodecTestUtils.wrap("0123456789ABCDEF"))); Assert.assertEquals(16, encoder.write(CodecTestUtils.wrap("0123456789ABCDEF"))); Mockito.verify(channel, Mockito.never()).write(Mockito.any()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("10\r\n0123456789ABCDEF\r\n10\r\n0123456789ABCDEF\r\n" + "10\r\n0123456789ABCDEF\r\n", s); } @Test public void testChunkExceed() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(16, 16); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkEncoder encoder = new ChunkEncoder(channel, outbuf, metrics); final ByteBuffer src = CodecTestUtils.wrap("0123456789ABCDEF"); Assert.assertEquals(16, encoder.write(src)); Assert.assertEquals(0, src.remaining()); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertEquals("4\r\n0123\r\n4\r\n4567\r\n4\r\n89AB\r\n4\r\nCDEF\r\n", s); } @Test public void testCodingEmptyBuffer() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkEncoder encoder = new ChunkEncoder(channel, outbuf, metrics); encoder.write(CodecTestUtils.wrap("12345")); encoder.write(CodecTestUtils.wrap("678")); encoder.write(CodecTestUtils.wrap("90")); final ByteBuffer empty = ByteBuffer.allocate(100); empty.flip(); encoder.write(empty); encoder.write(null); encoder.complete(); outbuf.flush(channel); final String s = channel.dump(Consts.ASCII); Assert.assertTrue(encoder.isCompleted()); Assert.assertEquals("5\r\n12345\r\n3\r\n678\r\n2\r\n90\r\n0\r\n\r\n", s); } @Test public void testCodingCompleted() throws Exception { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final ChunkEncoder encoder = new ChunkEncoder(channel, outbuf, metrics); encoder.write(CodecTestUtils.wrap("12345")); encoder.write(CodecTestUtils.wrap("678")); encoder.write(CodecTestUtils.wrap("90")); encoder.complete(); try { encoder.write(CodecTestUtils.wrap("more stuff")); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException ex) { // ignore } try { encoder.complete(); Assert.fail("IllegalStateException should have been thrown"); } catch (final IllegalStateException ex) { // ignore } } @Test public void testInvalidConstructor() { final WritableByteChannelMock channel = new WritableByteChannelMock(64); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128); try { new ChunkEncoder(null, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new ChunkEncoder(channel, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } try { new ChunkEncoder(channel, outbuf, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // ignore } } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/pool/0040755 0000000 0000000 00000000000 12613456023 027062 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000155 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/pool/TestBasicNIOConnPool.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/pool/TestBasicNIOConnP0100644 0000000 0000000 00000012676 12613456023 032203 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.pool; import org.apache.http.HttpHost; import org.apache.http.config.ConnectionConfig; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.pool.NIOConnFactory; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.net.SocketAddress; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class TestBasicNIOConnPool { static class LocalPool extends BasicNIOConnPool { public LocalPool( final ConnectingIOReactor ioreactor, final NIOConnFactory connFactory, final int connectTimeout) { super(ioreactor, connFactory, connectTimeout); } public LocalPool( final ConnectingIOReactor ioreactor, final ConnectionConfig config) { super(ioreactor, config); } @Override public void requestCompleted(final SessionRequest request) { super.requestCompleted(request); } } private BasicNIOConnFactory connFactory; private LocalPool pool; private HttpHost route; @Mock private ConnectingIOReactor reactor; @Mock private IOSession session; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); route = new HttpHost("localhost", 80, "http"); connFactory = new BasicNIOConnFactory(ConnectionConfig.DEFAULT); pool = new LocalPool(reactor, connFactory, 0); } @After public void tearDown() throws Exception { } @Test(expected=IllegalArgumentException.class) public void testNullConstructor() throws Exception { pool = new LocalPool(null, ConnectionConfig.DEFAULT); } @Test public void testCreateConnection() throws Exception { connFactory.create(route, session); } @Test public void testCreateEntry() throws Exception { final NHttpClientConnection conn = connFactory.create(route, session); final BasicNIOPoolEntry entry = pool.createEntry(route, conn); entry.close(); } @Test public void testTimeoutOnLeaseRelease() throws Exception { final HttpHost host = new HttpHost("somehost"); final SessionRequest sessionRequest = Mockito.mock(SessionRequest.class); Mockito.when(sessionRequest.getSession()).thenReturn(session); Mockito.when(sessionRequest.getAttachment()).thenReturn(host); Mockito.when(reactor.connect( Mockito.any(SocketAddress.class), Mockito.any(SocketAddress.class), Mockito.eq(host), Mockito.any(SessionRequestCallback.class))). thenReturn(sessionRequest); Mockito.when(session.getSocketTimeout()).thenReturn(999); final Future future1 = pool.lease(host, null, 10, TimeUnit.SECONDS, null); Mockito.verify(sessionRequest).setConnectTimeout(10000); pool.requestCompleted(sessionRequest); final BasicNIOPoolEntry entry1 = future1.get(); final NHttpClientConnection conn1 = entry1.getConnection(); Assert.assertNotNull(entry1); Assert.assertNotNull(conn1); Assert.assertEquals(999, entry1.getSocketTimeout()); Assert.assertEquals(999, conn1.getSocketTimeout()); Mockito.when(session.getSocketTimeout()).thenReturn(888); pool.release(entry1, true); Assert.assertEquals(888, entry1.getSocketTimeout()); Mockito.verify(session).setSocketTimeout(0); final Future future2 = pool.lease(host, null, 10, TimeUnit.SECONDS, null); final BasicNIOPoolEntry entry2 = future2.get(); final NHttpClientConnection conn2 = entry2.getConnection(); Assert.assertNotNull(entry2); Assert.assertNotNull(conn2); Assert.assertEquals(888, entry1.getSocketTimeout()); Mockito.verify(session).setSocketTimeout(888); } } httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/reactor/0040755 0000000 0000000 00000000000 12613456023 027550 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000163 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/reactor/TestSessionInOutBuffers.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/reactor/TestSessionInO0100644 0000000 0000000 00000056416 12613456023 032375 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import java.util.Arrays; import java.util.Collection; import org.apache.http.Consts; import org.apache.http.MessageConstraintException; import org.apache.http.config.MessageConstraints; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.DirectByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.util.CharArrayBuffer; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Simple tests for {@link SessionInputBuffer} and {@link SessionOutputBuffer}. */ @RunWith(Parameterized.class) public class TestSessionInOutBuffers { private final ByteBufferAllocator allocator; public TestSessionInOutBuffers(final ByteBufferAllocator allocator) { super(); this.allocator = allocator; } @Parameters public static Collection getParameters() { return Arrays.asList( new Object[] { HeapByteBufferAllocator.INSTANCE }, new Object[] { DirectByteBufferAllocator.INSTANCE }); } private static WritableByteChannel newChannel(final ByteArrayOutputStream outstream) { return Channels.newChannel(outstream); } private static ReadableByteChannel newChannel(final byte[] bytes) { return Channels.newChannel(new ByteArrayInputStream(bytes)); } private static ReadableByteChannel newChannel(final String s, final Charset charset) throws UnsupportedEncodingException { return Channels.newChannel(new ByteArrayInputStream(s.getBytes(charset))); } private static ReadableByteChannel newChannel(final String s) throws UnsupportedEncodingException { return newChannel(s, Consts.ASCII); } @Test public void testReadLineChunks() throws Exception { final SessionInputBuffer inbuf = new SessionInputBufferImpl(16, 16, null, this.allocator); ReadableByteChannel channel = newChannel("One\r\nTwo\r\nThree"); inbuf.fill(channel); final CharArrayBuffer line = new CharArrayBuffer(64); line.clear(); Assert.assertTrue(inbuf.readLine(line, false)); Assert.assertEquals("One", line.toString()); line.clear(); Assert.assertTrue(inbuf.readLine(line, false)); Assert.assertEquals("Two", line.toString()); line.clear(); Assert.assertFalse(inbuf.readLine(line, false)); channel = newChannel("\r\nFour"); inbuf.fill(channel); line.clear(); Assert.assertTrue(inbuf.readLine(line, false)); Assert.assertEquals("Three", line.toString()); inbuf.fill(channel); line.clear(); Assert.assertTrue(inbuf.readLine(line, true)); Assert.assertEquals("Four", line.toString()); line.clear(); Assert.assertFalse(inbuf.readLine(line, true)); } @Test public void testLineLimit() throws Exception { final String s = "LoooooooooooooooooooooooooOOOOOOOOOOOOOOOOOOoooooooooooooooooooooong line\r\n"; final CharArrayBuffer line = new CharArrayBuffer(64); final SessionInputBuffer inbuf1 = new SessionInputBufferImpl(128, 128, MessageConstraints.DEFAULT, null, this.allocator); final ReadableByteChannel channel1 = newChannel(s); inbuf1.fill(channel1); Assert.assertTrue(inbuf1.readLine(line, false)); line.clear(); final SessionInputBuffer inbuf2 = new SessionInputBufferImpl(128, 128, MessageConstraints.lineLen(10), null, this.allocator); final ReadableByteChannel channel2 = newChannel(s); inbuf2.fill(channel2); try { inbuf2.readLine(line, false); Assert.fail("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } } @Test public void testLineLimitBufferFull() throws Exception { final String s = "LoooooooooooooooooooooooooOOOOOOOOOOOOOOOOOOoooooooooooooooooooooong line\r\n"; final CharArrayBuffer line = new CharArrayBuffer(64); final SessionInputBuffer inbuf1 = new SessionInputBufferImpl(32, 32, MessageConstraints.DEFAULT, null, this.allocator); final ReadableByteChannel channel1 = newChannel(s); inbuf1.fill(channel1); Assert.assertFalse(inbuf1.readLine(line, false)); line.clear(); final SessionInputBuffer inbuf2 = new SessionInputBufferImpl(32, 32, MessageConstraints.lineLen(10), null, this.allocator); final ReadableByteChannel channel2 = newChannel(s); inbuf2.fill(channel2); try { inbuf2.readLine(line, false); Assert.fail("MessageConstraintException expected"); } catch (MessageConstraintException ex) { } } @Test public void testWriteLineChunks() throws Exception { final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(16, 16, null, this.allocator); final SessionInputBuffer inbuf = new SessionInputBufferImpl(16, 16, null, this.allocator); ReadableByteChannel inChannel = newChannel("One\r\nTwo\r\nThree"); inbuf.fill(inChannel); final CharArrayBuffer line = new CharArrayBuffer(64); line.clear(); Assert.assertTrue(inbuf.readLine(line, false)); Assert.assertEquals("One", line.toString()); outbuf.writeLine(line); line.clear(); Assert.assertTrue(inbuf.readLine(line, false)); Assert.assertEquals("Two", line.toString()); outbuf.writeLine(line); line.clear(); Assert.assertFalse(inbuf.readLine(line, false)); inChannel = newChannel("\r\nFour"); inbuf.fill(inChannel); line.clear(); Assert.assertTrue(inbuf.readLine(line, false)); Assert.assertEquals("Three", line.toString()); outbuf.writeLine(line); inbuf.fill(inChannel); line.clear(); Assert.assertTrue(inbuf.readLine(line, true)); Assert.assertEquals("Four", line.toString()); outbuf.writeLine(line); line.clear(); Assert.assertFalse(inbuf.readLine(line, true)); final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel outChannel = newChannel(outstream); outbuf.flush(outChannel); final String s = new String(outstream.toByteArray(), "US-ASCII"); Assert.assertEquals("One\r\nTwo\r\nThree\r\nFour\r\n", s); } @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 line 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 SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 16, null, this.allocator); for (final String teststr : teststrs) { outbuf.writeLine(teststr); } //this write operation should have no effect outbuf.writeLine((String)null); outbuf.writeLine((CharArrayBuffer)null); final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel outChannel = newChannel(outstream); outbuf.flush(outChannel); final ReadableByteChannel channel = newChannel(outstream.toByteArray()); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 16, null, this.allocator); inbuf.fill(channel); for (final String teststr : teststrs) { Assert.assertEquals(teststr, inbuf.readLine(true)); } Assert.assertNull(inbuf.readLine(true)); Assert.assertNull(inbuf.readLine(true)); } @Test public void testComplexReadWriteLine() throws Exception { final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 16, null, this.allocator); outbuf.write(ByteBuffer.wrap(new byte[] {'a', '\n'})); outbuf.write(ByteBuffer.wrap(new byte[] {'\r', '\n'})); outbuf.write(ByteBuffer.wrap(new byte[] {'\r', '\r', '\n'})); outbuf.write(ByteBuffer.wrap(new byte[] {'\n'})); final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 14; i++) { buffer.append("a"); } final String s1 = buffer.toString(); buffer.append("\r\n"); outbuf.write(ByteBuffer.wrap(buffer.toString().getBytes(Consts.ASCII))); buffer.setLength(0); for (int i = 0; i < 15; i++) { buffer.append("a"); } final String s2 = buffer.toString(); buffer.append("\r\n"); outbuf.write(ByteBuffer.wrap(buffer.toString().getBytes(Consts.ASCII))); buffer.setLength(0); for (int i = 0; i < 16; i++) { buffer.append("a"); } final String s3 = buffer.toString(); buffer.append("\r\n"); outbuf.write(ByteBuffer.wrap(buffer.toString().getBytes(Consts.ASCII))); outbuf.write(ByteBuffer.wrap(new byte[] {'a'})); final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel outChannel = newChannel(outstream); outbuf.flush(outChannel); final ReadableByteChannel channel = newChannel(outstream.toByteArray()); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 16, null, this.allocator); inbuf.fill(channel); Assert.assertEquals("a", inbuf.readLine(true)); Assert.assertEquals("", inbuf.readLine(true)); Assert.assertEquals("\r", inbuf.readLine(true)); Assert.assertEquals("", inbuf.readLine(true)); Assert.assertEquals(s1, inbuf.readLine(true)); Assert.assertEquals(s2, inbuf.readLine(true)); Assert.assertEquals(s3, inbuf.readLine(true)); Assert.assertEquals("a", inbuf.readLine(true)); Assert.assertNull(inbuf.readLine(true)); Assert.assertNull(inbuf.readLine(true)); } @Test public void testReadOneByte() throws Exception { // make the buffer larger than that of transmitter final byte[] out = new byte[40]; for (int i = 0; i < out.length; i++) { out[i] = (byte)('0' + i); } final ReadableByteChannel channel = newChannel(out); final SessionInputBuffer inbuf = new SessionInputBufferImpl(16, 16, null, this.allocator); while (inbuf.fill(channel) > 0) { } final byte[] in = new byte[40]; for (int i = 0; i < in.length; i++) { in[i] = (byte)inbuf.read(); } for (int i = 0; i < out.length; i++) { Assert.assertEquals(out[i], in[i]); } } @Test public void testReadByteBuffer() throws Exception { final byte[] pattern = "0123456789ABCDEF".getBytes(Consts.ASCII); final ReadableByteChannel channel = newChannel(pattern); final SessionInputBuffer inbuf = new SessionInputBufferImpl(4096, 1024, null, this.allocator); while (inbuf.fill(channel) > 0) { } final ByteBuffer dst = ByteBuffer.allocate(10); Assert.assertEquals(10, inbuf.read(dst)); dst.flip(); Assert.assertEquals(dst, ByteBuffer.wrap(pattern, 0, 10)); dst.clear(); Assert.assertEquals(6, inbuf.read(dst)); dst.flip(); Assert.assertEquals(dst, ByteBuffer.wrap(pattern, 10, 6)); } @Test public void testReadByteBufferWithMaxLen() throws Exception { final byte[] pattern = "0123456789ABCDEF".getBytes(Consts.ASCII); final ReadableByteChannel channel = newChannel(pattern); final SessionInputBuffer inbuf = new SessionInputBufferImpl(4096, 1024, null, this.allocator); while (inbuf.fill(channel) > 0) { } final ByteBuffer dst = ByteBuffer.allocate(16); Assert.assertEquals(10, inbuf.read(dst, 10)); dst.flip(); Assert.assertEquals(dst, ByteBuffer.wrap(pattern, 0, 10)); dst.clear(); Assert.assertEquals(3, inbuf.read(dst, 3)); dst.flip(); Assert.assertEquals(dst, ByteBuffer.wrap(pattern, 10, 3)); Assert.assertEquals(3, inbuf.read(dst, 20)); dst.flip(); Assert.assertEquals(dst, ByteBuffer.wrap(pattern, 13, 3)); } @Test public void testReadToChannel() throws Exception { final byte[] pattern = "0123456789ABCDEF".getBytes(Consts.ASCII); final ReadableByteChannel channel = newChannel(pattern); final SessionInputBuffer inbuf = new SessionInputBufferImpl(4096, 1024, null, this.allocator); while (inbuf.fill(channel) > 0) { } final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel dst = newChannel(outstream); Assert.assertEquals(16, inbuf.read(dst)); Assert.assertEquals(ByteBuffer.wrap(pattern), ByteBuffer.wrap(outstream.toByteArray())); } @Test public void testReadToChannelWithMaxLen() throws Exception { final byte[] pattern = "0123456789ABCDEF".getBytes(Consts.ASCII); final ReadableByteChannel channel = newChannel(pattern); final SessionInputBuffer inbuf = new SessionInputBufferImpl(4096, 1024, null, this.allocator); while (inbuf.fill(channel) > 0) { } final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel dst = newChannel(outstream); Assert.assertEquals(10, inbuf.read(dst, 10)); Assert.assertEquals(3, inbuf.read(dst, 3)); Assert.assertEquals(3, inbuf.read(dst, 10)); Assert.assertEquals(ByteBuffer.wrap(pattern), ByteBuffer.wrap(outstream.toByteArray())); } @Test public void testWriteByteBuffer() throws Exception { final byte[] pattern = "0123456789ABCDEF0123456789ABCDEF".getBytes(Consts.ASCII); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(4096, 1024, null, this.allocator); final ReadableByteChannel src = newChannel(pattern); outbuf.write(src); final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel channel = newChannel(outstream); while (outbuf.flush(channel) > 0) { } Assert.assertEquals(ByteBuffer.wrap(pattern), ByteBuffer.wrap(outstream.toByteArray())); } @Test public void testWriteFromChannel() throws Exception { final byte[] pattern = "0123456789ABCDEF0123456789ABCDEF".getBytes(Consts.ASCII); final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(4096, 1024, null, this.allocator); outbuf.write(ByteBuffer.wrap(pattern, 0, 16)); outbuf.write(ByteBuffer.wrap(pattern, 16, 10)); outbuf.write(ByteBuffer.wrap(pattern, 26, 6)); final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel channel = newChannel(outstream); while (outbuf.flush(channel) > 0) { } Assert.assertEquals(ByteBuffer.wrap(pattern), ByteBuffer.wrap(outstream.toByteArray())); } 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 SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 16, Consts.UTF_8.newEncoder(), this.allocator); for (int i = 0; i < 10; i++) { outbuf.writeLine(s1); outbuf.writeLine(s2); outbuf.writeLine(s3); } final ByteArrayOutputStream outstream = new ByteArrayOutputStream(); final WritableByteChannel outChannel = newChannel(outstream); outbuf.flush(outChannel); final byte[] tmp = outstream.toByteArray(); final ReadableByteChannel channel = newChannel(tmp); final SessionInputBuffer inbuf = new SessionInputBufferImpl(16, 16, Consts.UTF_8.newDecoder(), this.allocator); while (inbuf.fill(channel) > 0) { } for (int i = 0; i < 10; i++) { Assert.assertEquals(s1, inbuf.readLine(true)); Assert.assertEquals(s2, inbuf.readLine(true)); Assert.assertEquals(s3, inbuf.readLine(true)); } } @Test public void testInputMatchesBufferLength() throws Exception { final String s1 = "abcde"; final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 5, null, this.allocator); outbuf.writeLine(s1); } @Test(expected=CharacterCodingException.class) public void testMalformedInputActionReport() throws Exception { final String s = constructString(SWISS_GERMAN_HELLO); final byte[] tmp = s.getBytes(Consts.ISO_8859_1); final CharsetDecoder decoder = Consts.UTF_8.newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); final SessionInputBuffer inbuf = new SessionInputBufferImpl(16, 16, decoder, this.allocator); final ReadableByteChannel channel = newChannel(tmp); while (inbuf.fill(channel) > 0) { } inbuf.readLine(true); } @Test public void testMalformedInputActionIgnore() throws Exception { final String s = constructString(SWISS_GERMAN_HELLO); final byte[] tmp = s.getBytes(Consts.ISO_8859_1); final CharsetDecoder decoder = Consts.UTF_8.newDecoder(); decoder.onMalformedInput(CodingErrorAction.IGNORE); decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); final SessionInputBuffer inbuf = new SessionInputBufferImpl(16, 16, decoder, this.allocator); final ReadableByteChannel channel = newChannel(tmp); while (inbuf.fill(channel) > 0) { } final String result = inbuf.readLine(true); Assert.assertEquals("Grezi_zm", result); } @Test public void testMalformedInputActionReplace() throws Exception { final String s = constructString(SWISS_GERMAN_HELLO); final byte[] tmp = s.getBytes(Consts.ISO_8859_1); final CharsetDecoder decoder = Consts.UTF_8.newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPLACE); decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); final SessionInputBuffer inbuf = new SessionInputBufferImpl(16, 16, decoder, this.allocator); final ReadableByteChannel channel = newChannel(tmp); while (inbuf.fill(channel) > 0) { } final String result = inbuf.readLine(true); Assert.assertEquals("Gr\ufffdezi_z\ufffdm\ufffd", result); } @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 SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 16, encoder, this.allocator); outbuf.writeLine(s); } @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 SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 16, encoder, this.allocator); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final WritableByteChannel channel = newChannel(baos); outbuf.writeLine(s); outbuf.flush(channel); final String result = new String(baos.toByteArray(), "US-ASCII"); Assert.assertEquals("This text contains a circumflex !!!\r\n", result); } @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 SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 16, encoder, this.allocator); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final WritableByteChannel channel = newChannel(baos); outbuf.writeLine(s); outbuf.flush(channel); final String result = new String(baos.toByteArray(), "US-ASCII"); Assert.assertEquals("This text contains a circumflex ? !!!\r\n", result); } } ././@LongLink0100644 0000000 0000000 00000000171 12613460516 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/reactor/TestDefaultListeningIOReactor.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/reactor/TestDefaultLis0100644 0000000 0000000 00000017507 12613456023 032376 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.IOException; import java.net.BindException; import java.net.InetSocketAddress; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.http.HttpResponseInterceptor; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.nio.DefaultHttpServerIODispatch; import org.apache.http.nio.protocol.HttpAsyncService; import org.apache.http.nio.protocol.UriHttpAsyncRequestHandlerMapper; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.protocol.HttpProcessor; 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.junit.Assert; import org.junit.Test; /** * Basic tests for {@link DefaultListeningIOReactor}. */ public class TestDefaultListeningIOReactor { private static IOEventDispatch createIOEventDispatch() { final HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); final HttpAsyncService serviceHandler = new HttpAsyncService(httpproc, new UriHttpAsyncRequestHandlerMapper()); return new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT); } @Test public void testEndpointUpAndDown() throws Exception { final IOEventDispatch eventDispatch = createIOEventDispatch(); final IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build(); final ListeningIOReactor ioreactor = new DefaultListeningIOReactor(config); final Thread t = new Thread(new Runnable() { @Override public void run() { try { ioreactor.execute(eventDispatch); } catch (final IOException ex) { } } }); t.start(); Set endpoints = ioreactor.getEndpoints(); Assert.assertNotNull(endpoints); Assert.assertEquals(0, endpoints.size()); final ListenerEndpoint endpoint1 = ioreactor.listen(new InetSocketAddress(0)); endpoint1.waitFor(); final ListenerEndpoint endpoint2 = ioreactor.listen(new InetSocketAddress(0)); endpoint2.waitFor(); final int port = ((InetSocketAddress) endpoint2.getAddress()).getPort(); endpoints = ioreactor.getEndpoints(); Assert.assertNotNull(endpoints); Assert.assertEquals(2, endpoints.size()); endpoint1.close(); endpoints = ioreactor.getEndpoints(); Assert.assertNotNull(endpoints); Assert.assertEquals(1, endpoints.size()); final ListenerEndpoint endpoint = endpoints.iterator().next(); Assert.assertEquals(port, ((InetSocketAddress) endpoint.getAddress()).getPort()); ioreactor.shutdown(1000); t.join(1000); Assert.assertEquals(IOReactorStatus.SHUT_DOWN, ioreactor.getStatus()); } @Test public void testEndpointAlreadyBoundFatal() throws Exception { final IOEventDispatch eventDispatch = createIOEventDispatch(); final IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build(); final ListeningIOReactor ioreactor = new DefaultListeningIOReactor(config); final CountDownLatch latch = new CountDownLatch(1); final Thread t = new Thread(new Runnable() { @Override public void run() { try { ioreactor.execute(eventDispatch); Assert.fail("IOException should have been thrown"); } catch (final IOException ex) { latch.countDown(); } } }); t.start(); final ListenerEndpoint endpoint1 = ioreactor.listen(new InetSocketAddress(0)); endpoint1.waitFor(); final int port = ((InetSocketAddress) endpoint1.getAddress()).getPort(); final ListenerEndpoint endpoint2 = ioreactor.listen(new InetSocketAddress(port)); endpoint2.waitFor(); Assert.assertNotNull(endpoint2.getException()); // I/O reactor is now expected to be shutting down latch.await(2000, TimeUnit.MILLISECONDS); Assert.assertTrue(ioreactor.getStatus().compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0); final Set endpoints = ioreactor.getEndpoints(); Assert.assertNotNull(endpoints); Assert.assertEquals(0, endpoints.size()); ioreactor.shutdown(1000); t.join(1000); Assert.assertEquals(IOReactorStatus.SHUT_DOWN, ioreactor.getStatus()); } @Test public void testEndpointAlreadyBoundNonFatal() throws Exception { final IOEventDispatch eventDispatch = createIOEventDispatch(); final IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build(); final DefaultListeningIOReactor ioreactor = new DefaultListeningIOReactor(config); ioreactor.setExceptionHandler(new IOReactorExceptionHandler() { @Override public boolean handle(final IOException ex) { return (ex instanceof BindException); } @Override public boolean handle(final RuntimeException ex) { return false; } }); final Thread t = new Thread(new Runnable() { @Override public void run() { try { ioreactor.execute(eventDispatch); } catch (final IOException ex) { } } }); t.start(); final ListenerEndpoint endpoint1 = ioreactor.listen(new InetSocketAddress(9999)); endpoint1.waitFor(); final ListenerEndpoint endpoint2 = ioreactor.listen(new InetSocketAddress(9999)); endpoint2.waitFor(); Assert.assertNotNull(endpoint2.getException()); // Sleep a little to make sure the I/O reactor is not shutting down Thread.sleep(500); Assert.assertEquals(IOReactorStatus.ACTIVE, ioreactor.getStatus()); ioreactor.shutdown(1000); t.join(1000); Assert.assertEquals(IOReactorStatus.SHUT_DOWN, ioreactor.getStatus()); } } ././@LongLink0100644 0000000 0000000 00000000156 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/reactor/ExceptionEventTest.javahttpcomponents-core-4.4.4/httpcore-nio/src/test/java/org/apache/http/impl/nio/reactor/ExceptionEvent0100644 0000000 0000000 00000004145 12613456023 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.nio.reactor; import java.util.Date; import org.junit.Assert; import org.junit.Test; public class ExceptionEventTest { @Test public void testGetCause() { final NullPointerException npe = new NullPointerException("npe"); ExceptionEvent ee = new ExceptionEvent(npe); Assert.assertSame(npe, ee.getCause()); ee = new ExceptionEvent(npe, new Date()); Assert.assertSame(npe, ee.getCause()); } @Test public void testGetTimestamp() { final NullPointerException npe = new NullPointerException("npe"); ExceptionEvent ee = new ExceptionEvent(npe); Assert.assertNotNull(ee.getTimestamp()); ee = new ExceptionEvent(npe, new Date(1234567890L)); Assert.assertEquals(new Date(1234567890L), ee.getTimestamp()); } @Test public void testToString() { Assert.assertNotNull(new ExceptionEvent(new NullPointerException())); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/0040755 0000000 0000000 00000000000 12613456027 020424 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/0040755 0000000 0000000 00000000000 12613456024 021342 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/0040755 0000000 0000000 00000000000 12613456024 022131 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/0040755 0000000 0000000 00000000000 12613456024 023352 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/0040755 0000000 0000000 00000000000 12613456025 024332 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/0040755 0000000 0000000 00000000000 12613456027 025121 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/ContentEncoderChannel.java0100644 0000000 0000000 00000003726 12613456025 032172 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; /** * A {@link WritableByteChannel} that delegates to a {@link ContentEncoder}. * Attempts to close this channel are ignored, and {@link #isOpen} always * returns {@code true}. * * @since 4.0 */ public class ContentEncoderChannel implements WritableByteChannel { private final ContentEncoder contentEncoder; public ContentEncoderChannel(final ContentEncoder contentEncoder) { this.contentEncoder = contentEncoder; } @Override public int write(final ByteBuffer src) throws IOException { return contentEncoder.write(src); } @Override public void close() {} @Override public boolean isOpen() { return true; } } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageWriterFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageWriterFactory.j0100644 0000000 0000000 00000002760 12613456026 032364 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import org.apache.http.HttpMessage; import org.apache.http.nio.reactor.SessionOutputBuffer; /** * Factory for {@link NHttpMessageWriter} instances. * * @since 4.3 */ public interface NHttpMessageWriterFactory { NHttpMessageWriter create(SessionOutputBuffer buffer); } ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServerEventHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServerEventHandler.jav0100644 0000000 0000000 00000013500 12613456026 032342 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import org.apache.http.HttpException; /** * Abstract server-side HTTP event handler. * * @since 4.2 */ public interface NHttpServerEventHandler { /** * Triggered when a new incoming connection is created. * * @param conn new incoming connection HTTP connection. */ void connected( NHttpServerConnection conn) throws IOException, HttpException; /** * 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 * {@link #inputReady(NHttpServerConnection, ContentDecoder)} calls * to transfer the request content. * * @see NHttpServerConnection * * @param conn HTTP connection that contains a new HTTP request */ void requestReceived( NHttpServerConnection conn) throws IOException, HttpException; /** * 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 incoming content, * input event notifications can be temporarily suspended using * {@link IOControl} interface (super interface of {@link NHttpServerConnection}). *

* Please note that the {@link NHttpServerConnection} and {@link ContentDecoder} * objects are not thread-safe and should only be used within the context of * this method call. The {@link IOControl} object can be shared and used on other * thread to resume input event notifications when the handler is capable of * processing more content. * * @see NHttpServerConnection * @see ContentDecoder * @see IOControl * * @param conn HTTP connection that can produce a new portion of the * incoming request content. * @param decoder The content decoder to use to read content. */ void inputReady( NHttpServerConnection conn, ContentDecoder decoder) throws IOException, HttpException; /** * Triggered when the connection is ready to accept a new HTTP response. * The protocol handler does not have to submit a response if it is not * ready. * * @see NHttpServerConnection * * @param conn HTTP connection that contains an HTTP response */ void responseReady( NHttpServerConnection conn) throws IOException, HttpException; /** * 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 outgoing content, * output event notifications can be temporarily suspended using * {@link IOControl} interface (super interface of {@link NHttpServerConnection}). *

* Please note that the {@link NHttpServerConnection} and {@link ContentEncoder} * objects are not thread-safe and should only be used within the context of * this method call. The {@link IOControl} object can be shared and used on other * thread to resume output event notifications when more content is made available. * * @see NHttpServerConnection * @see ContentEncoder * @see IOControl * * @param conn HTTP connection that can accommodate a new portion * of the outgoing response content. * @param encoder The content encoder to use to write content. */ void outputReady( NHttpServerConnection conn, ContentEncoder encoder) throws IOException, HttpException; /** * Triggered when the connection is closed by the opposite end point * (half-closed). * * @param conn half-closed HTTP connection. */ void endOfInput( NHttpServerConnection conn) throws IOException; /** * Triggered when no input is detected on this connection over the * maximum period of inactivity. * * @param conn HTTP connection that caused timeout condition. */ void timeout( NHttpServerConnection conn) throws IOException; /** * Triggered when the connection is closed. * * @param conn closed HTTP connection. */ void closed(NHttpServerConnection conn); /** * Triggered if an error occurs during the HTTP exchange. * * @param conn HTTP connection that caused an I/O error * @param ex exception */ void exception(NHttpServerConnection conn, Exception ex); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/ContentDecoderChannel.java0100644 0000000 0000000 00000003661 12613456026 032157 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; /** * A {@link ReadableByteChannel} that delegates to a {@link ContentDecoder}. * Attempts to close this channel are ignored, and {@link #isOpen} always * returns {@code true}. * * @since 4.0 */ public class ContentDecoderChannel implements ReadableByteChannel { private final ContentDecoder decoder; public ContentDecoderChannel(final ContentDecoder decoder) { this.decoder = decoder; } @Override public int read(final ByteBuffer dst) throws IOException { return decoder.read(dst); } @Override public void close() {} @Override public boolean isOpen() { return true; } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/ContentDecoder.java0100644 0000000 0000000 00000004140 12613456025 030656 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import java.nio.ByteBuffer; /** * Abstract HTTP content decoder. HTTP content decoders can be used * to read entity content from the underlying channel in small * chunks and apply the required coding transformation. * * @since 4.0 */ public interface ContentDecoder { /** * Reads a portion of content from the underlying channel * * @param dst The buffer into which entity content is to be transferred * @return The number of bytes read, possibly zero, or -1 if the * channel has reached end-of-stream * @throws IOException if I/O error occurs while reading content */ int read(ByteBuffer dst) throws IOException; /** * Returns {@code true} if the entity has been received in its * entirety. * * @return {@code true} if all the content has been consumed, * {@code false} otherwise. */ boolean isCompleted(); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServiceHandler.java0100644 0000000 0000000 00000011640 12613456026 031636 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import org.apache.http.HttpException; /** * Abstract server-side HTTP protocol handler. * * @since 4.0 * * @deprecated (4.2) use {@link NHttpServerEventHandler} */ @Deprecated public interface NHttpServiceHandler { /** * Triggered when a new incoming connection is created. * * @param conn new incoming connection HTTP connection. */ void connected(NHttpServerConnection conn); /** * 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 * {@link #inputReady(NHttpServerConnection, ContentDecoder)} calls * to transfer the request content. * * @see NHttpServerConnection * * @param conn HTTP connection that contains a new HTTP request */ void requestReceived(NHttpServerConnection conn); /** * 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 be temporarily suspended using * {@link IOControl} interface. * * @see NHttpServerConnection * @see ContentDecoder * @see IOControl * * @param conn HTTP connection that can produce a new portion of the * incoming request content. * @param decoder The content decoder to use to read content. */ void inputReady(NHttpServerConnection conn, ContentDecoder decoder); /** * Triggered when the connection is ready to accept a new HTTP response. * The protocol handler does not have to submit a response if it is not * ready. * * @see NHttpServerConnection * * @param conn HTTP connection that contains an HTTP response */ void responseReady(NHttpServerConnection conn); /** * 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 * {@link IOControl} interface. * * @see NHttpServerConnection * @see ContentEncoder * @see IOControl * * @param conn HTTP connection that can accommodate a new portion * of the outgoing response content. * @param encoder The content encoder to use to write content. */ void outputReady(NHttpServerConnection conn, ContentEncoder encoder); /** * Triggered when an I/O error occurs while reading from or writing * to the underlying channel. * * @param conn HTTP connection that caused an I/O error * @param ex I/O exception */ void exception(NHttpServerConnection conn, IOException ex); /** * Triggered when an HTTP protocol violation occurs while receiving * an HTTP request. * * @param conn HTTP connection that caused an HTTP protocol violation * @param ex HTTP protocol violation exception */ void exception(NHttpServerConnection conn, HttpException ex); /** * Triggered when no input is detected on this connection over the * maximum period of inactivity. * * @param conn HTTP connection that caused timeout condition. */ void timeout(NHttpServerConnection conn); /** * Triggered when the connection is closed. * * @param conn closed HTTP connection. */ void closed(NHttpServerConnection conn); } ././@LongLink0100644 0000000 0000000 00000000150 12613460516 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageParserFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageParserFactory.j0100644 0000000 0000000 00000003100 12613456025 032330 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import org.apache.http.HttpMessage; import org.apache.http.config.MessageConstraints; import org.apache.http.nio.reactor.SessionInputBuffer; /** * Factory for {@link NHttpMessageParser} instances. * * @since 4.3 */ public interface NHttpMessageParserFactory { NHttpMessageParser create(SessionInputBuffer buffer, MessageConstraints constraints); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientHandler.java0100644 0000000 0000000 00000011773 12613456026 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.nio; import java.io.IOException; import org.apache.http.HttpException; /** * Abstract client-side HTTP protocol handler. * * @since 4.0 * * @deprecated (4.2) use {@link NHttpClientEventHandler} */ @Deprecated public interface NHttpClientHandler { /** * Triggered when a new outgoing connection is created. * * @param conn new outgoing HTTP connection. * @param attachment an object that was attached to the session request */ void connected(NHttpClientConnection conn, Object attachment); /** * Triggered when the connection is ready to accept a new HTTP request. * The protocol handler does not have to submit a request if it is not * ready. * * @see NHttpClientConnection * * @param conn HTTP connection that is ready to accept a new HTTP request. */ void requestReady(NHttpClientConnection conn); /** * 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 by a series of * {@link #inputReady(NHttpClientConnection, ContentDecoder)} calls * to transfer the response content. * * @see NHttpClientConnection * * @param conn HTTP connection that contains an HTTP response */ void responseReceived(NHttpClientConnection conn); /** * 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 * {@link IOControl} interface. * * @see NHttpClientConnection * @see ContentDecoder * @see IOControl * * @param conn HTTP connection that can produce a new portion of the * incoming response content. * @param decoder The content decoder to use to read content. */ void inputReady(NHttpClientConnection conn, ContentDecoder decoder); /** * 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 * {@link IOControl} interface. * * @see NHttpClientConnection * @see ContentEncoder * @see IOControl * * @param conn HTTP connection that can accommodate a new portion * of the outgoing request content. * @param encoder The content encoder to use to write content. */ void outputReady(NHttpClientConnection conn, ContentEncoder encoder); /** * Triggered when an I/O error occurs while reading from or writing * to the underlying channel. * * @param conn HTTP connection that caused an I/O error * @param ex I/O exception */ void exception(NHttpClientConnection conn, IOException ex); /** * Triggered when an HTTP protocol violation occurs while receiving * an HTTP response. * * @param conn HTTP connection that caused an HTTP protocol violation * @param ex HTTP protocol violation exception */ void exception(NHttpClientConnection conn, HttpException ex); /** * Triggered when no input is detected on this connection over the * maximum period of inactivity. * * @param conn HTTP connection that caused timeout condition. */ void timeout(NHttpClientConnection conn); /** * Triggered when the connection is closed. * * @param conn closed HTTP connection. */ void closed(NHttpClientConnection conn); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServerIOTarget.java0100644 0000000 0000000 00000003627 12613456026 031613 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; /** * Extended version of the {@link NHttpServerConnection} used by * {@link org.apache.http.nio.reactor.IOEventDispatch } implementations * to inform server-side connection objects of I/O events. * * @since 4.0 * * @deprecated (4.2) no longer used */ @Deprecated public interface NHttpServerIOTarget extends NHttpServerConnection { /** * Triggered when the connection is ready to consume input. * * @param handler the server protocol handler. */ void consumeInput(NHttpServiceHandler handler); /** * Triggered when the connection is ready to produce output. * * @param handler the server protocol handler. */ void produceOutput(NHttpServiceHandler handler); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/IOControl.java0100644 0000000 0000000 00000004544 12613456025 027636 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; /** * Connection input/output control interface. It can be used to control interest * in I/O event notifications for non-blocking HTTP connections. *

* Implementations of this interface are expected to be threading safe. * Therefore it can be used to request / suspend I/O event notifications from * any thread of execution. * * @since 4.0 */ public interface IOControl { /** * Requests event notifications to be triggered when the underlying * channel is ready for input operations. */ void requestInput(); /** * Suspends event notifications about the underlying channel being * ready for input operations. */ void suspendInput(); /** * Requests event notifications to be triggered when the underlying * channel is ready for output operations. */ void requestOutput(); /** * Suspends event notifications about the underlying channel being * ready for output operations. */ void suspendOutput(); /** * Shuts down the underlying channel. * * @throws IOException in an error occurs */ void shutdown() throws IOException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/package-info.java0100644 0000000 0000000 00000002442 12613456026 030306 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 for asynchronous, event * driven communication. */ package org.apache.http.nio; httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpConnection.java0100644 0000000 0000000 00000006371 12613456026 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.nio; import org.apache.http.HttpConnection; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.protocol.HttpContext; /** * Abstract non-blocking HTTP connection interface. Each connection contains an * HTTP execution context, which can be used to maintain a processing state, * as well as the actual {@link HttpRequest} and {@link HttpResponse} that are * being transmitted over this connection. Both the request and * the response objects can be {@code null} if there is no incoming or * outgoing message currently being transferred. *

* Please note 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. * However, the {@link IOControl} interface is fully threading safe and can be * manipulated from any thread. * * @since 4.0 */ public interface NHttpConnection extends HttpConnection, IOControl { public static final int ACTIVE = 0; public static final int CLOSING = 1; public static final int CLOSED = 2; /** * Returns status of the connection: *

* {@link #ACTIVE}: connection is active. *

* {@link #CLOSING}: connection is being closed. *

* {@link #CLOSED}: connection has been closed. * * @return connection status. */ int getStatus(); /** * Returns the current HTTP request if one is being received / transmitted. * Otherwise returns {@code null}. * * @return HTTP request, if available, {@code null} otherwise. */ HttpRequest getHttpRequest(); /** * Returns the current HTTP response if one is being received / transmitted. * Otherwise returns {@code null}. * * @return HTTP response, if available, {@code null} otherwise. */ HttpResponse getHttpResponse(); /** * Returns an HTTP execution context associated with this connection. * @return HTTP context */ HttpContext getContext(); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientIOTarget.java0100644 0000000 0000000 00000003624 12613456027 031561 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; /** * Extended version of the {@link NHttpClientConnection} used by * {@link org.apache.http.nio.reactor.IOEventDispatch} implementations * to inform client-side connection objects of I/O events. * * @since 4.0 * * @deprecated (4.2) no longer used */ @Deprecated public interface NHttpClientIOTarget extends NHttpClientConnection { /** * Triggered when the connection is ready to consume input. * * @param handler the client protocol handler. */ void consumeInput(NHttpClientHandler handler); /** * Triggered when the connection is ready to produce output. * * @param handler the client protocol handler. */ void produceOutput(NHttpClientHandler handler); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientConnection.java0100644 0000000 0000000 00000004742 12613456026 032203 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; /** * Abstract non-blocking client-side HTTP connection interface. It can be used * to submit HTTP requests and asynchronously receive HTTP responses. * * @see NHttpConnection * * @since 4.0 */ public interface NHttpClientConnection extends NHttpConnection { /** * Submits {@link HttpRequest} to be sent to the target server. * * @param request HTTP request * @throws IOException if I/O error occurs while submitting the request * @throws HttpException if the HTTP request violates the HTTP protocol. */ void submitRequest(HttpRequest request) throws IOException, HttpException; /** * Returns {@code true} if an HTTP request has been submitted to the * target server. * * @return {@code true} if an HTTP request has been submitted, * {@code false} otherwise. */ boolean isRequestSubmitted(); /** * Resets output state. This method can be used to prematurely terminate * processing of the outgoing HTTP request. */ void resetOutput(); /** * Resets input state. This method can be used to prematurely terminate * processing of the incoming HTTP response. */ void resetInput(); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageParser.java0100644 0000000 0000000 00000004665 12613456026 031512 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import org.apache.http.HttpException; import org.apache.http.HttpMessage; /** * Abstract HTTP message parser for non-blocking connections. * * @since 4.0 */ public interface NHttpMessageParser { /** * Resets the parser. The parser will be ready to start parsing another * HTTP message. */ void reset(); /** * Fills the internal buffer of the parser with input data from the * given {@link ReadableByteChannel}. * * @param channel the input channel * @return number of bytes read. * @throws IOException in case of an I/O error. */ int fillBuffer(ReadableByteChannel channel) throws IOException; /** * Attempts to parse a complete message head from the content of the * internal buffer. If the message in the input buffer is incomplete * this method will return {@code null}. * * @return HTTP message head, if available, {@code null} otherwise. * @throws IOException in case of an I/O error. * @throws HttpException in case the HTTP message is malformed or * violates the HTTP protocol. */ T parse() throws IOException, HttpException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/ContentEncoder.java0100644 0000000 0000000 00000004325 12613456026 030676 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import java.nio.ByteBuffer; /** * Abstract HTTP content encoder. HTTP content encoders can be used * to apply the required coding transformation and write entity * content to the underlying channel in small chunks. * * @since 4.0 */ public interface ContentEncoder { /** * Writes a portion of entity content to the underlying channel. * * @param src The buffer from which content is to be retrieved * @return The number of bytes read, possibly zero * @throws IOException if I/O error occurs while writing content */ int write(ByteBuffer src) throws IOException; /** * Terminates the content stream. * * @throws IOException if I/O error occurs while writing content */ void complete() throws IOException; /** * Returns {@code true} if the entity has been transferred in its * entirety. * * @return {@code true} if all the content has been produced, * {@code false} otherwise. */ boolean isCompleted(); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/FileContentEncoder.java0100644 0000000 0000000 00000004151 12613456026 031473 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import java.nio.channels.FileChannel; /** * A content encoder capable of transferring data directly from a {@link FileChannel} * * @since 4.0 */ public interface FileContentEncoder extends ContentEncoder { /** * Transfers a portion of entity content from the given file channel * to the underlying network channel. * * @param src the source FileChannel to transfer data from. * @param position * The position within the file at which the transfer is to begin; * must be non-negative * @param count * The maximum number of bytes to be transferred; must be * non-negative * @throws IOException if some I/O error occurs. * @return The number of bytes, possibly zero, * that were actually transferred */ long transfer(FileChannel src, long position, long count) throws IOException; } ././@LongLink0100644 0000000 0000000 00000000145 12613460516 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpConnectionFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpConnectionFactory.java0100644 0000000 0000000 00000002655 12613456025 032374 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import org.apache.http.nio.reactor.IOSession; /** * Factory for {@link NHttpConnection} instances. * * @since 4.2 */ public interface NHttpConnectionFactory { T createConnection(IOSession session); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageWriter.java0100644 0000000 0000000 00000003612 12613456025 031520 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpMessage; /** * Abstract HTTP message writer for non-blocking connections. * * @since 4.0 */ public interface NHttpMessageWriter { /** * Resets the writer. The writer will be ready to start serializing another * HTTP message. */ void reset(); /** * Serializes out the HTTP message head. * * @param message HTTP message. * @throws IOException in case of an I/O error. * @throws HttpException in case the HTTP message is malformed or * violates the HTTP protocol. */ void write(T message) throws IOException, HttpException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServerConnection.java0100644 0000000 0000000 00000004747 12613456025 032237 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpResponse; /** * Abstract non-blocking server-side HTTP connection interface. It can be used * to receive HTTP requests and asynchronously submit HTTP responses. * * @see NHttpConnection * * @since 4.0 */ public interface NHttpServerConnection extends NHttpConnection { /** * Submits {link @HttpResponse} to be sent to the client. * * @param response HTTP response * * @throws IOException if I/O error occurs while submitting the response * @throws HttpException if the HTTP response violates the HTTP protocol. */ void submitResponse(HttpResponse response) throws IOException, HttpException; /** * Returns {@code true} if an HTTP response has been submitted to the * client. * * @return {@code true} if an HTTP response has been submitted, * {@code false} otherwise. */ boolean isResponseSubmitted(); /** * Resets output state. This method can be used to prematurely terminate * processing of the incoming HTTP request. */ void resetInput(); /** * Resets input state. This method can be used to prematurely terminate * processing of the outgoing HTTP response. */ void resetOutput(); } ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientEventHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientEventHandler.jav0100644 0000000 0000000 00000013671 12613456027 032324 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import org.apache.http.HttpException; /** * Abstract client-side HTTP protocol handler. * * @since 4.2 */ public interface NHttpClientEventHandler { /** * Triggered when a new outgoing connection is created. * * @param conn new outgoing HTTP connection. * @param attachment an object that was attached to the session request */ void connected( NHttpClientConnection conn, Object attachment) throws IOException, HttpException; /** * Triggered when the connection is ready to accept a new HTTP request. * The protocol handler does not have to submit a request if it is not * ready. * * @see NHttpClientConnection * * @param conn HTTP connection that is ready to accept a new HTTP request. */ void requestReady( NHttpClientConnection conn) throws IOException, HttpException; /** * 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 by a series of * {@link #inputReady(NHttpClientConnection, ContentDecoder)} calls * to transfer the response content. * * @see NHttpClientConnection * * @param conn HTTP connection that contains an HTTP response */ void responseReceived( NHttpClientConnection conn) throws IOException, HttpException; /** * 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 incoming content, * input event notifications can be temporarily suspended using * {@link IOControl} interface (super interface of {@link NHttpClientConnection}). *

* Please note that the {@link NHttpClientConnection} and {@link ContentDecoder} * objects are not thread-safe and should only be used within the context of * this method call. The {@link IOControl} object can be shared and used on other * thread to resume input event notifications when the handler is capable of * processing more content. * * @see NHttpClientConnection * @see ContentDecoder * @see IOControl * * @param conn HTTP connection that can produce a new portion of the * incoming response content. * @param decoder The content decoder to use to read content. */ void inputReady( NHttpClientConnection conn, ContentDecoder decoder) throws IOException, HttpException; /** * 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 outgoing content, * output event notifications can be temporarily suspended using * {@link IOControl} interface (super interface of {@link NHttpClientConnection}). *

* Please note that the {@link NHttpClientConnection} and {@link ContentEncoder} * objects are not thread-safe and should only be used within the context of * this method call. The {@link IOControl} object can be shared and used on other * thread to resume output event notifications when more content is made available. * * @see NHttpClientConnection * @see ContentEncoder * @see IOControl * * @param conn HTTP connection that can accommodate a new portion * of the outgoing request content. * @param encoder The content encoder to use to write content. */ void outputReady( NHttpClientConnection conn, ContentEncoder encoder) throws IOException, HttpException; /** * Triggered when the connection is closed by the opposite end point * (half-closed). * * @param conn half-closed HTTP connection. */ void endOfInput( NHttpClientConnection conn) throws IOException; /** * Triggered when no input is detected on this connection over the * maximum period of inactivity. * * @param conn HTTP connection that caused timeout condition. */ void timeout( NHttpClientConnection conn) throws IOException, HttpException; /** * Triggered when the connection is closed. * * @param conn closed HTTP connection. */ void closed(NHttpClientConnection conn); /** * Triggered if an error occurs during the HTTP exchange. * * @param conn HTTP connection that caused an I/O error * @param ex exception */ void exception(NHttpClientConnection conn, Exception ex); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/FileContentDecoder.java0100644 0000000 0000000 00000004627 12613456025 031470 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio; import java.io.IOException; import java.nio.channels.FileChannel; /** * A content decoder capable of transferring data directly to a {@link FileChannel} * * @since 4.0 */ public interface FileContentDecoder extends ContentDecoder { /** * Transfers a portion of entity content from the underlying network channel * into the given file channel.
* * Warning: Many implementations cannot write beyond the length of the file. * If the position exceeds the channel's size, some implementations * may throw an IOException. * * @param dst the target FileChannel to transfer data into. * @param position * The position within the file at which the transfer is to begin; * must be non-negative. * Must be less than or equal to the size of the file * @param count * The maximum number of bytes to be transferred; must be * non-negative * @throws IOException if some I/O error occurs. * @return The number of bytes, possibly zero, * that were actually transferred */ long transfer(FileChannel dst, long position, long count) throws IOException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/params/0040755 0000000 0000000 00000000000 12613456025 026402 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/params/package-info.java0100644 0000000 0000000 00000002362 12613456025 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 * . * */ /** * Deprecated. * @deprecated (4.3). */ package org.apache.http.nio.params; ././@LongLink0100644 0000000 0000000 00000000146 12613460516 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/params/NIOReactorPNames.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/params/NIOReactorPNames.jav0100644 0000000 0000000 00000005170 12613456025 032155 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.params; /** * Parameter names for I/O reactors. * * @since 4.0 * * @deprecated (4.2) use {@link org.apache.http.impl.nio.reactor.IOReactorConfig} */ @Deprecated public interface NIOReactorPNames { /** * Determines the size of the content input/output buffers used * to buffer data while receiving or transmitting HTTP messages. *

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

*/ public static final String CONTENT_BUFFER_SIZE = "http.nio.content-buffer-size"; /** * Determines the time interval in milliseconds at which the * I/O reactor wakes up to check for timed out sessions and session requests. *

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

*/ public static final String SELECT_INTERVAL = "http.nio.select-interval"; /** * Determines the grace period the I/O reactors are expected to block * waiting for individual worker threads to terminate cleanly. *

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

*/ public static final String GRACE_PERIOD = "http.nio.grace-period"; /** * Determines whether interestOps() queueing is enabled for the I/O reactors. *

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

* * @since 4.1 */ public static final String INTEREST_OPS_QUEUEING = "http.nio.interest-ops-queueing"; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/0040755 0000000 0000000 00000000000 12613456026 026761 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000151 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncExchange.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncExchange.0100644 0000000 0000000 00000006727 12613456026 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.nio.protocol; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.concurrent.Cancellable; /** * {@code HttpAsyncExchange} represents a server-side HTTP message exchange * where an HTTP response can be deferred without blocking the I/O event thread * and triggered asynchronously at a later point of later time. * * @since 4.2 */ public interface HttpAsyncExchange { /** * Returns the received HTTP request message. * * @return received HTTP request message. */ HttpRequest getRequest(); /** * Returns the default HTTP response message. Once ready the response * message can submitted using {@link #submitResponse()} method. * * @return default HTTP response message. */ HttpResponse getResponse(); /** * Submits the default HTTP response and completed the message exchange. * If the response encloses an {@link org.apache.http.HttpEntity} instance * the entity is also expected to implement the * {@link org.apache.http.nio.entity.HttpAsyncContentProducer } * interface for efficient content streaming to a non-blocking HTTP * connection. * * @throws IllegalStateException if a response has already been submitted. */ void submitResponse(); /** * Submits an HTTP response using a custom * {@link HttpAsyncResponseProducer}. * * @throws IllegalStateException if a response has already been submitted. */ void submitResponse(HttpAsyncResponseProducer responseProducer); /** * Determines whether or not the message exchange has been completed. * * @return {@code true} if the message exchange has been completed, * {@code false} otherwise. */ boolean isCompleted(); /** * Sets {@link 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. */ void setCallback(Cancellable cancellable); /** * Sets timeout for this message exchange. */ void setTimeout(int timeout); /** * Returns timeout for this message exchange. */ int getTimeout(); } ././@LongLink0100644 0000000 0000000 00000000161 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncResponseConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncResponseC0100644 0000000 0000000 00000010721 12613456026 032441 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.Closeable; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.concurrent.Cancellable; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; /** * {@code HttpAsyncResponseConsumer} is a callback interface whose methods * get invoked to process an HTTP response message and to stream message * content from a non-blocking HTTP connection on the client side. * * @param the result type of response processing. * @since 4.2 */ public interface HttpAsyncResponseConsumer extends Closeable, Cancellable { /** * Invoked when a HTTP response message is received. Please note * that the {@link #consumeContent(ContentDecoder, IOControl)} method * will be invoked only if the response messages has a content entity * enclosed. * * @param response HTTP response message. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void responseReceived(HttpResponse response) throws IOException, HttpException; /** * Invoked to process a chunk of content from the {@link ContentDecoder}. * The {@link IOControl} interface can be used to suspend input event * notifications if the consumer is temporarily unable to process content. *

* The consumer can use the {@link ContentDecoder#isCompleted()} method * to find out whether or not the message content has been fully consumed. *

* Please note that the {@link ContentDecoder} object is not thread-safe and * should only be used within the context of this method call. * The {@link IOControl} object can be shared and used on other thread * to resume input event notifications when the consumer is capable of * processing more content. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. * @throws IOException in case of an I/O error */ void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Invoked to signal that the response has been fully processed. * * @param context HTTP context */ void responseCompleted(HttpContext context); /** * Invoked to signal that the response processing terminated abnormally. * * @param ex exception */ void failed(Exception ex); /** * Returns an exception in case of an abnormal termination. This method * returns {@code null} if the response processing is still ongoing * or if it completed successfully. * * @see #isDone() */ Exception getException(); /** * Returns a result of the response processing, when available. This method * returns {@code null} if the response processing is still ongoing. * * @see #isDone() */ T getResult(); /** * Determines whether or not the response processing completed. If the * response processing terminated normally {@link #getResult()} * can be used to obtain the result. If the response processing terminated * abnormally {@link #getException()} can be used to obtain the cause. */ boolean isDone(); } ././@LongLink0100644 0000000 0000000 00000000165 12613460516 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestHandlerMapper.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestHa0100644 0000000 0000000 00000003441 12613456026 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.nio.protocol; import org.apache.http.HttpRequest; /** * {@code HttpAsyncRequestHandlerMapper} can be used to resolve an instance * of {@link HttpAsyncRequestHandler} matching a particular {@link HttpRequest}. * Usually the resolved request handler will be used to process the request. * * @since 4.3 */ public interface HttpAsyncRequestHandlerMapper { /** * Looks up a handler matching the given request. * * @param request the request * @return HTTP request handler or {@code null} if no match * is found. */ HttpAsyncRequestHandler lookup(HttpRequest request); } ././@LongLink0100644 0000000 0000000 00000000160 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncRequestHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncRequestH0100644 0000000 0000000 00000005132 12613456026 032402 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.annotation.Immutable; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.util.Args; /** * Basic implementation of {@link HttpAsyncRequestHandler} that delegates * the process of request handling to a {@link HttpRequestHandler}. Please note * that this handler buffers request content in memory and should be used for * relatively small request messages. * * @since 4.2 */ @Immutable public class BasicAsyncRequestHandler implements HttpAsyncRequestHandler { private final HttpRequestHandler handler; public BasicAsyncRequestHandler(final HttpRequestHandler handler) { super(); Args.notNull(handler, "Request handler"); this.handler = handler; } @Override public HttpAsyncRequestConsumer processRequest(final HttpRequest request, final HttpContext context) { return new BasicAsyncRequestConsumer(); } @Override public void handle( final HttpRequest request, final HttpAsyncExchange httpexchange, final HttpContext context) throws HttpException, IOException { this.handler.handle(request, httpexchange.getResponse(), context); httpexchange.submitResponse(); } } ././@LongLink0100644 0000000 0000000 00000000160 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestCo0100644 0000000 0000000 00000010722 12613456026 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.nio.protocol; import java.io.Closeable; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; /** * {@code HttpAsyncRequestConsumer} is a callback interface whose methods * get invoked to process an HTTP request message and to stream message * content from a non-blocking HTTP connection on the server side. * * @param the result type of request processing. * @since 4.2 */ public interface HttpAsyncRequestConsumer extends Closeable { /** * Invoked when a HTTP request message is received. Please note * that the {@link #consumeContent(ContentDecoder, IOControl)} method * will be invoked only for if the request message implements * {@link org.apache.http.HttpEntityEnclosingRequest} interface and * has a content entity enclosed. * * @param request HTTP request message. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void requestReceived(HttpRequest request) throws HttpException, IOException; /** * Invoked to process a chunk of content from the {@link ContentDecoder}. * The {@link IOControl} interface can be used to suspend input event * notifications if the consumer is temporarily unable to process content. *

* The consumer can use the {@link ContentDecoder#isCompleted()} method * to find out whether or not the message content has been fully consumed. *

* Please note that the {@link ContentDecoder} object is not thread-safe and * should only be used within the context of this method call. * The {@link IOControl} object can be shared and used on other thread * to resume input event notifications when the consumer is capable of * processing more content. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. * @throws IOException in case of an I/O error */ void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Invoked to signal that the request has been fully processed. * * @param context HTTP context */ void requestCompleted(HttpContext context); /** * Invoked to signal that the request processing terminated abnormally. * * @param ex exception */ void failed(Exception ex); /** * Returns an exception in case of an abnormal termination. This method * returns {@code null} if the request execution is still ongoing * or if it completed successfully. * * @see #isDone() */ Exception getException(); /** * Returns a result of the request execution, when available. This method * returns {@code null} if the request execution is still ongoing. * * @see #isDone() */ T getResult(); /** * Determines whether or not the request execution completed. If the * request processing terminated normally {@link #getResult()} * can be used to obtain the result. If the request processing terminated * abnormally {@link #getException()} can be used to obtain the cause. */ boolean isDone(); } ././@LongLink0100644 0000000 0000000 00000000160 12613460516 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestExecutor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestEx0100644 0000000 0000000 00000050626 12613456026 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.nio.protocol; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.http.ConnectionClosedException; import org.apache.http.ExceptionLogger; 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.HttpVersion; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.annotation.Immutable; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientEventHandler; import org.apache.http.nio.NHttpConnection; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * {@code HttpAsyncRequestExecutor} is a fully asynchronous HTTP client side * protocol handler based on the NIO (non-blocking) I/O model. * {@code HttpAsyncRequestExecutor} translates individual events fired through * the {@link NHttpClientEventHandler} interface into logically related HTTP * message exchanges. *

The caller is expected to pass an instance of * {@link HttpAsyncClientExchangeHandler} to be used for the next series * of HTTP message exchanges through the connection context using * {@link #HTTP_HANDLER} attribute. HTTP exchange sequence is considered * complete when the {@link HttpAsyncClientExchangeHandler#isDone()} method * returns {@code true}. The {@link HttpAsyncRequester} utility class can * be used to facilitate initiation of asynchronous HTTP request execution. *

* Individual {@code HttpAsyncClientExchangeHandler} are expected to make use of * a {@link org.apache.http.protocol.HttpProcessor} to generate mandatory protocol * headers for all outgoing messages and apply common, cross-cutting message * transformations to all incoming and outgoing messages. * {@code HttpAsyncClientExchangeHandler}s can delegate implementation of * application specific content generation and processing to * a {@link HttpAsyncRequestProducer} and a {@link HttpAsyncResponseConsumer}. * * @see HttpAsyncClientExchangeHandler * * @since 4.2 */ @Immutable public class HttpAsyncRequestExecutor implements NHttpClientEventHandler { public static final int DEFAULT_WAIT_FOR_CONTINUE = 3000; public static final String HTTP_HANDLER = "http.nio.exchange-handler"; private final int waitForContinue; private final ExceptionLogger exceptionLogger; /** * Creates new instance of {@code HttpAsyncRequestExecutor}. * @param waitForContinue wait for continue time period. * @param exceptionLogger Exception logger. If {@code null} * {@link ExceptionLogger#NO_OP} will be used. Please note that the exception * logger will be only used to log I/O exception thrown while closing * {@link java.io.Closeable} objects (such as {@link org.apache.http.HttpConnection}). * * @since 4.4 */ public HttpAsyncRequestExecutor( final int waitForContinue, final ExceptionLogger exceptionLogger) { super(); this.waitForContinue = Args.positive(waitForContinue, "Wait for continue time"); this.exceptionLogger = exceptionLogger != null ? exceptionLogger : ExceptionLogger.NO_OP; } /** * Creates new instance of HttpAsyncRequestExecutor. * * @since 4.3 */ public HttpAsyncRequestExecutor(final int waitForContinue) { this(waitForContinue, null); } public HttpAsyncRequestExecutor() { this(DEFAULT_WAIT_FOR_CONTINUE, null); } @Override public void connected( final NHttpClientConnection conn, final Object attachment) throws IOException, HttpException { final State state = new State(); final HttpContext context = conn.getContext(); context.setAttribute(HTTP_EXCHANGE_STATE, state); requestReady(conn); } @Override public void closed(final NHttpClientConnection conn) { final State state = getState(conn); final HttpAsyncClientExchangeHandler handler = getHandler(conn); if (state != null) { if (state.getRequestState() != MessageState.READY || state.getResponseState() != MessageState.READY) { if (handler != null) { handler.failed(new ConnectionClosedException("Connection closed unexpectedly")); } } } if (state == null || (handler != null && handler.isDone())) { closeHandler(handler); } } @Override public void exception( final NHttpClientConnection conn, final Exception cause) { shutdownConnection(conn); final HttpAsyncClientExchangeHandler handler = getHandler(conn); if (handler != null) { handler.failed(cause); } else { log(cause); } } @Override public void requestReady( final NHttpClientConnection conn) throws IOException, HttpException { final State state = getState(conn); Asserts.notNull(state, "Connection state"); Asserts.check(state.getRequestState() == MessageState.READY || state.getRequestState() == MessageState.COMPLETED, "Unexpected request state %s", state.getRequestState()); if (state.getRequestState() == MessageState.COMPLETED) { conn.suspendOutput(); return; } final HttpContext context = conn.getContext(); final HttpAsyncClientExchangeHandler handler; synchronized (context) { handler = getHandler(conn); if (handler == null || handler.isDone()) { conn.suspendOutput(); return; } } final boolean pipelined = handler.getClass().getAnnotation(Pipelined.class) != null; final HttpRequest request = handler.generateRequest(); if (request == null) { conn.suspendOutput(); return; } final ProtocolVersion version = request.getRequestLine().getProtocolVersion(); if (pipelined && version.lessEquals(HttpVersion.HTTP_1_0)) { throw new ProtocolException(version + " cannot be used with request pipelining"); } state.setRequest(request); if (pipelined) { state.getRequestQueue().add(request); } if (request instanceof HttpEntityEnclosingRequest) { final boolean expectContinue = ((HttpEntityEnclosingRequest) request).expectContinue(); if (expectContinue && pipelined) { throw new ProtocolException("Expect-continue handshake cannot be used with request pipelining"); } conn.submitRequest(request); if (expectContinue) { final int timeout = conn.getSocketTimeout(); state.setTimeout(timeout); conn.setSocketTimeout(this.waitForContinue); state.setRequestState(MessageState.ACK_EXPECTED); } else { final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { state.setRequestState(MessageState.BODY_STREAM); } else { handler.requestCompleted(); state.setRequestState(pipelined ? MessageState.READY : MessageState.COMPLETED); } } } else { conn.submitRequest(request); handler.requestCompleted(); state.setRequestState(pipelined ? MessageState.READY : MessageState.COMPLETED); } } @Override public void outputReady( final NHttpClientConnection conn, final ContentEncoder encoder) throws IOException, HttpException { final State state = getState(conn); Asserts.notNull(state, "Connection state"); Asserts.check(state.getRequestState() == MessageState.BODY_STREAM || state.getRequestState() == MessageState.ACK_EXPECTED, "Unexpected request state %s", state.getRequestState()); final HttpAsyncClientExchangeHandler handler = getHandler(conn); Asserts.notNull(handler, "Client exchange handler"); if (state.getRequestState() == MessageState.ACK_EXPECTED) { conn.suspendOutput(); return; } handler.produceContent(encoder, conn); if (encoder.isCompleted()) { handler.requestCompleted(); final boolean pipelined = handler.getClass().getAnnotation(Pipelined.class) != null; state.setRequestState(pipelined ? MessageState.READY : MessageState.COMPLETED); } } @Override public void responseReceived( final NHttpClientConnection conn) throws HttpException, IOException { final State state = getState(conn); Asserts.notNull(state, "Connection state"); Asserts.check(state.getResponseState() == MessageState.READY, "Unexpected request state %s", state.getResponseState()); final HttpAsyncClientExchangeHandler handler = getHandler(conn); Asserts.notNull(handler, "Client exchange handler"); final boolean pipelined = handler.getClass().getAnnotation(Pipelined.class) != null; final HttpRequest request; if (pipelined) { request = state.getRequestQueue().poll(); Asserts.notNull(request, "HTTP request"); } else { request = state.getRequest(); if (request == null) { throw new HttpException("Out of sequence response"); } } final HttpResponse response = conn.getHttpResponse(); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < HttpStatus.SC_OK) { // 1xx intermediate response if (statusCode != HttpStatus.SC_CONTINUE) { throw new ProtocolException( "Unexpected response: " + response.getStatusLine()); } if (state.getRequestState() == MessageState.ACK_EXPECTED) { final int timeout = state.getTimeout(); conn.setSocketTimeout(timeout); conn.requestOutput(); state.setRequestState(MessageState.BODY_STREAM); } return; } state.setResponse(response); if (state.getRequestState() == MessageState.ACK_EXPECTED) { final int timeout = state.getTimeout(); conn.setSocketTimeout(timeout); conn.resetOutput(); state.setRequestState(MessageState.COMPLETED); } else if (state.getRequestState() == MessageState.BODY_STREAM) { // Early response conn.resetOutput(); conn.suspendOutput(); state.setRequestState(MessageState.COMPLETED); state.invalidate(); } handler.responseReceived(response); state.setResponseState(MessageState.BODY_STREAM); if (!canResponseHaveBody(request, response)) { response.setEntity(null); conn.resetInput(); processResponse(conn, state, handler); } } @Override public void inputReady( final NHttpClientConnection conn, final ContentDecoder decoder) throws IOException, HttpException { final State state = getState(conn); Asserts.notNull(state, "Connection state"); Asserts.check(state.getResponseState() == MessageState.BODY_STREAM, "Unexpected request state %s", state.getResponseState()); final HttpAsyncClientExchangeHandler handler = getHandler(conn); Asserts.notNull(handler, "Client exchange handler"); handler.consumeContent(decoder, conn); if (decoder.isCompleted()) { processResponse(conn, state, handler); } } @Override public void endOfInput(final NHttpClientConnection conn) throws IOException { final State state = getState(conn); if (state != null) { if (state.getRequestState().compareTo(MessageState.READY) != 0) { state.invalidate(); } final HttpAsyncClientExchangeHandler handler = getHandler(conn); if (handler != null) { if (state.isValid()) { handler.inputTerminated(); } else { handler.failed(new ConnectionClosedException("Connection closed")); } } } // Closing connection in an orderly manner and // waiting for output buffer to get flushed. // Do not want to wait indefinitely, though, in case // the opposite end is not reading if (conn.getSocketTimeout() <= 0) { conn.setSocketTimeout(1000); } conn.close(); } @Override public void timeout( final NHttpClientConnection conn) throws IOException { final State state = getState(conn); if (state != null) { if (state.getRequestState() == MessageState.ACK_EXPECTED) { final int timeout = state.getTimeout(); conn.setSocketTimeout(timeout); conn.requestOutput(); state.setRequestState(MessageState.BODY_STREAM); state.setTimeout(0); return; } else { state.invalidate(); final HttpAsyncClientExchangeHandler handler = getHandler(conn); if (handler != null) { handler.failed(new SocketTimeoutException()); handler.close(); } } } if (conn.getStatus() == NHttpConnection.ACTIVE) { conn.close(); if (conn.getStatus() == NHttpConnection.CLOSING) { // Give the connection some grace time to // close itself nicely conn.setSocketTimeout(250); } } else { conn.shutdown(); } } /** * This method can be used to log I/O exception thrown while closing * {@link java.io.Closeable} objects (such as * {@link org.apache.http.HttpConnection}}). * * @param ex I/O exception thrown by {@link java.io.Closeable#close()} */ protected void log(final Exception ex) { this.exceptionLogger.log(ex); } private State getState(final NHttpConnection conn) { return (State) conn.getContext().getAttribute(HTTP_EXCHANGE_STATE); } private HttpAsyncClientExchangeHandler getHandler(final NHttpConnection conn) { return (HttpAsyncClientExchangeHandler) conn.getContext().getAttribute(HTTP_HANDLER); } private void shutdownConnection(final NHttpConnection conn) { try { conn.shutdown(); } catch (final IOException ex) { log(ex); } } private void closeHandler(final HttpAsyncClientExchangeHandler handler) { if (handler != null) { try { handler.close(); } catch (final IOException ioex) { log(ioex); } } } private void processResponse( final NHttpClientConnection conn, final State state, final HttpAsyncClientExchangeHandler handler) throws IOException, HttpException { if (!state.isValid()) { conn.close(); } handler.responseCompleted(); final boolean pipelined = handler.getClass().getAnnotation(Pipelined.class) != null; if (!pipelined) { state.setRequestState(MessageState.READY); state.setRequest(null); } state.setResponseState(MessageState.READY); state.setResponse(null); if (!handler.isDone() && conn.isOpen()) { conn.requestOutput(); } } private boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) { final String method = request.getRequestLine().getMethod(); final int status = response.getStatusLine().getStatusCode(); if (method.equalsIgnoreCase("HEAD")) { return false; } if (method.equalsIgnoreCase("CONNECT") && status < 300) { return false; } return status >= HttpStatus.SC_OK && status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT; } static final String HTTP_EXCHANGE_STATE = "http.nio.http-exchange-state"; static class State { private final Queue requestQueue; private volatile MessageState requestState; private volatile MessageState responseState; private volatile HttpRequest request; private volatile HttpResponse response; private volatile boolean valid; private volatile int timeout; State() { super(); this.requestQueue = new ConcurrentLinkedQueue(); this.valid = true; this.requestState = MessageState.READY; this.responseState = MessageState.READY; } public MessageState getRequestState() { return this.requestState; } public void setRequestState(final MessageState state) { this.requestState = state; } public MessageState getResponseState() { return this.responseState; } public void setResponseState(final MessageState state) { this.responseState = state; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public Queue getRequestQueue() { return this.requestQueue; } public int getTimeout() { return this.timeout; } public void setTimeout(final int timeout) { this.timeout = timeout; } public boolean isValid() { return this.valid; } public void invalidate() { this.valid = false; } @Override public String toString() { final StringBuilder buf = new StringBuilder(); buf.append("request state: "); buf.append(this.requestState); buf.append("; request: "); if (this.request != null) { buf.append(this.request.getRequestLine()); } buf.append("; response state: "); buf.append(this.responseState); buf.append("; response: "); if (this.response != null) { buf.append(this.response.getStatusLine()); } buf.append("; valid: "); buf.append(this.valid); buf.append(";"); return buf.toString(); } } } ././@LongLink0100644 0000000 0000000 00000000152 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NullRequestHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NullRequestHandler0100644 0000000 0000000 00000004316 12613456026 032466 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.protocol.HttpContext; class NullRequestHandler implements HttpAsyncRequestHandler { public NullRequestHandler() { super(); } @Override public HttpAsyncRequestConsumer processRequest( final HttpRequest request, final HttpContext context) { return new NullRequestConsumer(); } @Override public void handle( final Object obj, final HttpAsyncExchange httpexchange, final HttpContext context) { final HttpResponse response = httpexchange.getResponse(); response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); httpexchange.submitResponse(new ErrorResponseProducer( response, new NStringEntity("Service not implemented", ContentType.TEXT_PLAIN), true)); } } ././@LongLink0100644 0000000 0000000 00000000152 12613460516 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequester.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequester0100644 0000000 0000000 00000056405 12613456026 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.nio.protocol; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.concurrent.Future; import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.ExceptionLogger; import org.apache.http.HttpHost; import org.apache.http.annotation.Immutable; import org.apache.http.concurrent.BasicFuture; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.params.HttpParams; import org.apache.http.pool.ConnPool; import org.apache.http.pool.PoolEntry; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; /** * {@code HttpAsyncRequester} is a utility class that can be used * in conjunction with {@link HttpAsyncRequestExecutor} to initiate execution * of asynchronous HTTP requests. * * @see HttpAsyncRequestExecutor * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable public class HttpAsyncRequester { private final HttpProcessor httpprocessor; private final ConnectionReuseStrategy connReuseStrategy; private final ExceptionLogger exceptionLogger; /** * @deprecated (4.3) use {@link HttpAsyncRequester#HttpAsyncRequester(HttpProcessor, * ConnectionReuseStrategy)} */ @Deprecated public HttpAsyncRequester( final HttpProcessor httpprocessor, final ConnectionReuseStrategy reuseStrategy, final HttpParams params) { this(httpprocessor, reuseStrategy); } /** * Creates new instance of {@code HttpAsyncRequester}. * @param httpprocessor HTTP protocol processor. * @param connReuseStrategy Connection re-use strategy. If {@code null} * {@link DefaultConnectionReuseStrategy#INSTANCE} will be used. * @param exceptionLogger Exception logger. If {@code null} * {@link ExceptionLogger#NO_OP} will be used. Please note that the exception * logger will be only used to log I/O exception thrown while closing * {@link java.io.Closeable} objects (such as {@link org.apache.http.HttpConnection}). * * @since 4.4 */ public HttpAsyncRequester( final HttpProcessor httpprocessor, final ConnectionReuseStrategy connReuseStrategy, final ExceptionLogger exceptionLogger) { super(); this.httpprocessor = Args.notNull(httpprocessor, "HTTP processor"); this.connReuseStrategy = connReuseStrategy != null ? connReuseStrategy : DefaultConnectionReuseStrategy.INSTANCE; this.exceptionLogger = exceptionLogger != null ? exceptionLogger : ExceptionLogger.NO_OP; } /** * Creates new instance of HttpAsyncRequester. * * @since 4.3 */ public HttpAsyncRequester( final HttpProcessor httpprocessor, final ConnectionReuseStrategy connReuseStrategy) { this(httpprocessor, connReuseStrategy, (ExceptionLogger) null); } /** * Creates new instance of HttpAsyncRequester. * * @since 4.3 */ public HttpAsyncRequester(final HttpProcessor httpprocessor) { this(httpprocessor, null); } /** * Initiates asynchronous HTTP request execution. * * @param the result type of request execution. * @param requestProducer request producer. * @param responseConsumer response consumer. * @param conn underlying HTTP connection. * @param context HTTP context * @param callback future callback. * @return future representing pending completion of the operation. */ public Future execute( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final NHttpClientConnection conn, final HttpContext context, final FutureCallback callback) { Args.notNull(requestProducer, "HTTP request producer"); Args.notNull(responseConsumer, "HTTP response consumer"); Args.notNull(conn, "HTTP connection"); Args.notNull(context, "HTTP context"); final BasicAsyncClientExchangeHandler handler = new BasicAsyncClientExchangeHandler( requestProducer, responseConsumer, callback, context, conn, this.httpprocessor, this.connReuseStrategy); initExecution(handler, conn); return handler.getFuture(); } private void initExecution( final HttpAsyncClientExchangeHandler handler, final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); synchronized (context) { context.setAttribute(HttpAsyncRequestExecutor.HTTP_HANDLER, handler); if (!conn.isOpen()) { handler.failed(new ConnectionClosedException("Connection closed")); } else { conn.requestOutput(); } } if (handler.isDone()) { try { handler.close(); } catch (final IOException ex) { log(ex); } } } /** * Initiates asynchronous HTTP request execution. * * @param the result type of request execution. * @param requestProducer request producer. * @param responseConsumer response consumer. * @param conn underlying HTTP connection. * @param context HTTP context * @return future representing pending completion of the operation. */ public Future execute( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final NHttpClientConnection conn, final HttpContext context) { return execute(requestProducer, responseConsumer, conn, context, null); } /** * Initiates asynchronous HTTP request execution. * * @param the result type of request execution. * @param requestProducer request producer. * @param responseConsumer response consumer. * @param conn underlying HTTP connection. * @return future representing pending completion of the operation. */ public Future execute( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final NHttpClientConnection conn) { return execute(requestProducer, responseConsumer, conn, new BasicHttpContext()); } /** * Initiates asynchronous HTTP request execution. * * @param the result type of request execution. * @param the connection pool entry type. * @param requestProducer request producer. * @param responseConsumer response consumer. * @param connPool pool of persistent reusable connections. * @param context HTTP context * @param callback future callback. * @return future representing pending completion of the operation. */ public > Future execute( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final ConnPool connPool, final HttpContext context, final FutureCallback callback) { Args.notNull(requestProducer, "HTTP request producer"); Args.notNull(responseConsumer, "HTTP response consumer"); Args.notNull(connPool, "HTTP connection pool"); Args.notNull(context, "HTTP context"); final BasicFuture future = new BasicFuture(callback); final HttpHost target = requestProducer.getTarget(); connPool.lease(target, null, new ConnRequestCallback( future, requestProducer, responseConsumer, connPool, context)); return future; } /** * Initiates asynchronous pipelined HTTP request execution. * * @param the result type of request execution. * @param the connection pool entry type. * @param target target host. * @param requestProducers list of request producers. * @param responseConsumers list of response consumers. * @param connPool pool of persistent reusable connections. * @param context HTTP context * @param callback future callback. * @return future representing pending completion of the operation. * * @since 4.4 */ public > Future> executePipelined( final HttpHost target, final List requestProducers, final List> responseConsumers, final ConnPool connPool, final HttpContext context, final FutureCallback> callback) { Args.notNull(target, "HTTP target"); Args.notEmpty(requestProducers, "Request producer list"); Args.notEmpty(responseConsumers, "Response consumer list"); Args.notNull(connPool, "HTTP connection pool"); Args.notNull(context, "HTTP context"); final BasicFuture> future = new BasicFuture>(callback); connPool.lease(target, null, new ConnPipelinedRequestCallback( future, requestProducers, responseConsumers, connPool, context)); return future; } /** * Initiates asynchronous HTTP request execution. This method automatically releases * the given pool entry once request execution is completed (successfully or unsuccessfully). * * @param the result type of request execution. * @param the connection pool entry type. * @param requestProducer request producer. * @param responseConsumer response consumer. * @param poolEntry leased pool entry. It will be automatically released * back to the pool when execution is completed. * @param connPool pool of persistent reusable connections. * @param context HTTP context * @param callback future callback. * @return future representing pending completion of the operation. * * @since 4.3 */ public > Future execute( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final E poolEntry, final ConnPool connPool, final HttpContext context, final FutureCallback callback) { Args.notNull(requestProducer, "HTTP request producer"); Args.notNull(responseConsumer, "HTTP response consumer"); Args.notNull(connPool, "HTTP connection pool"); Args.notNull(poolEntry, "Pool entry"); Args.notNull(context, "HTTP context"); final BasicFuture future = new BasicFuture(callback); final NHttpClientConnection conn = poolEntry.getConnection(); final BasicAsyncClientExchangeHandler handler = new BasicAsyncClientExchangeHandler( requestProducer, responseConsumer, new RequestExecutionCallback(future, poolEntry, connPool), context, conn, this.httpprocessor, this.connReuseStrategy); initExecution(handler, conn); return future; } /** * Initiates asynchronous pipelined HTTP request execution. This method automatically releases * the given pool entry once request execution is completed (successfully or unsuccessfully). * * @param the result type of request execution. * @param the connection pool entry type. * @param requestProducers list of request producers. * @param responseConsumers list of response consumers. * @param poolEntry leased pool entry. It will be automatically released * back to the pool when execution is completed. * @param connPool pool of persistent reusable connections. * @param context HTTP context * @param callback future callback. * @return future representing pending completion of the operation. * * @since 4.4 */ public > Future> executePipelined( final List requestProducers, final List> responseConsumers, final E poolEntry, final ConnPool connPool, final HttpContext context, final FutureCallback> callback) { Args.notEmpty(requestProducers, "Request producer list"); Args.notEmpty(responseConsumers, "Response consumer list"); Args.notNull(connPool, "HTTP connection pool"); Args.notNull(poolEntry, "Pool entry"); Args.notNull(context, "HTTP context"); final BasicFuture> future = new BasicFuture>(callback); final NHttpClientConnection conn = poolEntry.getConnection(); final PipeliningClientExchangeHandler handler = new PipeliningClientExchangeHandler( requestProducers, responseConsumers, new RequestExecutionCallback, E>(future, poolEntry, connPool), context, conn, this.httpprocessor, this.connReuseStrategy); initExecution(handler, conn); return future; } /** * Initiates asynchronous HTTP request execution. * * @param the result type of request execution. * @param the connection pool entry type. * @param requestProducer request producer. * @param responseConsumer response consumer. * @param connPool pool of persistent reusable connections. * @param context HTTP context * @return future representing pending completion of the operation. */ public > Future execute( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final ConnPool connPool, final HttpContext context) { return execute(requestProducer, responseConsumer, connPool, context, null); } /** * Initiates asynchronous HTTP request execution. * * @param the result type of request execution. * @param the connection pool entry type. * @param requestProducer request producer. * @param responseConsumer response consumer. * @param connPool pool of persistent reusable connections. * @return future representing pending completion of the operation. */ public > Future execute( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final ConnPool connPool) { return execute(requestProducer, responseConsumer, connPool, new BasicHttpContext()); } class ConnRequestCallback> implements FutureCallback { private final BasicFuture requestFuture; private final HttpAsyncRequestProducer requestProducer; private final HttpAsyncResponseConsumer responseConsumer; private final ConnPool connPool; private final HttpContext context; ConnRequestCallback( final BasicFuture requestFuture, final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final ConnPool connPool, final HttpContext context) { super(); this.requestFuture = requestFuture; this.requestProducer = requestProducer; this.responseConsumer = responseConsumer; this.connPool = connPool; this.context = context; } @Override public void completed(final E result) { if (this.requestFuture.isDone()) { this.connPool.release(result, true); return; } final NHttpClientConnection conn = result.getConnection(); final BasicAsyncClientExchangeHandler handler = new BasicAsyncClientExchangeHandler( this.requestProducer, this.responseConsumer, new RequestExecutionCallback(this.requestFuture, result, this.connPool), this.context, conn, httpprocessor, connReuseStrategy); initExecution(handler, conn); } @Override public void failed(final Exception ex) { try { try { this.responseConsumer.failed(ex); } finally { releaseResources(); } } finally { this.requestFuture.failed(ex); } } @Override public void cancelled() { try { try { this.responseConsumer.cancel(); } finally { releaseResources(); } } finally { this.requestFuture.cancel(true); } } public void releaseResources() { close(requestProducer); close(responseConsumer); } } class ConnPipelinedRequestCallback> implements FutureCallback { private final BasicFuture> requestFuture; private final List requestProducers; private final List> responseConsumers; private final ConnPool connPool; private final HttpContext context; ConnPipelinedRequestCallback( final BasicFuture> requestFuture, final List requestProducers, final List> responseConsumers, final ConnPool connPool, final HttpContext context) { super(); this.requestFuture = requestFuture; this.requestProducers = requestProducers; this.responseConsumers = responseConsumers; this.connPool = connPool; this.context = context; } @Override public void completed(final E result) { if (this.requestFuture.isDone()) { this.connPool.release(result, true); return; } final NHttpClientConnection conn = result.getConnection(); final PipeliningClientExchangeHandler handler = new PipeliningClientExchangeHandler( this.requestProducers, this.responseConsumers, new RequestExecutionCallback, E>(this.requestFuture, result, this.connPool), this.context, conn, httpprocessor, connReuseStrategy); initExecution(handler, conn); } @Override public void failed(final Exception ex) { try { try { for (HttpAsyncResponseConsumer responseConsumer: this.responseConsumers) { responseConsumer.failed(ex); } } finally { releaseResources(); } } finally { this.requestFuture.failed(ex); } } @Override public void cancelled() { try { try { for (HttpAsyncResponseConsumer responseConsumer: this.responseConsumers) { responseConsumer.cancel(); } } finally { releaseResources(); } } finally { this.requestFuture.cancel(true); } } public void releaseResources() { for (HttpAsyncRequestProducer requestProducer: this.requestProducers) { close(requestProducer); } for (HttpAsyncResponseConsumer responseConsumer: this.responseConsumers) { close(responseConsumer); } } } class RequestExecutionCallback> implements FutureCallback { private final BasicFuture future; private final E poolEntry; private final ConnPool connPool; RequestExecutionCallback( final BasicFuture future, final E poolEntry, final ConnPool connPool) { super(); this.future = future; this.poolEntry = poolEntry; this.connPool = connPool; } @Override public void completed(final T result) { try { this.connPool.release(this.poolEntry, true); } finally { this.future.completed(result); } } @Override public void failed(final Exception ex) { try { this.connPool.release(this.poolEntry, false); } finally { this.future.failed(ex); } } @Override public void cancelled() { try { this.connPool.release(this.poolEntry, false); } finally { this.future.cancel(true); } } } /** * This method can be used to log I/O exception thrown while closing * {@link java.io.Closeable} objects (such as * {@link org.apache.http.HttpConnection}}). * * @param ex I/O exception thrown by {@link java.io.Closeable#close()} */ protected void log(final Exception ex) { this.exceptionLogger.log(ex); } private void close(final Closeable closeable) { try { closeable.close(); } catch (IOException ex) { log(ex); } } } ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncRequestConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncRequestC0100644 0000000 0000000 00000006577 12613456026 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.nio.protocol; import java.io.IOException; import org.apache.http.ContentTooLongException; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpRequest; import org.apache.http.entity.ContentType; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.ContentBufferEntity; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.nio.util.SimpleInputBuffer; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Asserts; /** * Basic implementation of {@link HttpAsyncRequestConsumer}. Please note that * this consumer buffers request content in memory and should be used for * relatively small request messages. * * @since 4.2 */ public class BasicAsyncRequestConsumer extends AbstractAsyncRequestConsumer { private volatile HttpRequest request; private volatile SimpleInputBuffer buf; public BasicAsyncRequestConsumer() { super(); } @Override protected void onRequestReceived(final HttpRequest request) throws IOException { this.request = request; } @Override protected void onEntityEnclosed( final HttpEntity entity, final ContentType contentType) throws IOException { long len = entity.getContentLength(); if (len > Integer.MAX_VALUE) { throw new ContentTooLongException("Entity content is too long: " + len); } if (len < 0) { len = 4096; } this.buf = new SimpleInputBuffer((int) len, new HeapByteBufferAllocator()); ((HttpEntityEnclosingRequest) this.request).setEntity( new ContentBufferEntity(entity, this.buf)); } @Override protected void onContentReceived( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { Asserts.notNull(this.buf, "Content buffer"); this.buf.consumeContent(decoder); } @Override protected void releaseResources() { this.request = null; this.buf = null; } @Override protected HttpRequest buildResult(final HttpContext context) { return this.request; } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/Pipelined.java0100644 0000000 0000000 00000002775 12613456026 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.nio.protocol; 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; @Documented @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Pipelined { } ././@LongLink0100644 0000000 0000000 00000000164 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/AbstractAsyncRequestConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/AbstractAsyncReque0100644 0000000 0000000 00000014470 12613456026 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.nio.protocol; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.entity.ContentType; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; /** * Abstract {@link HttpAsyncRequestConsumer} implementation that relieves its * subclasses from having to manage internal state and provides a number of protected * event methods that they need to implement. * * @since 4.2 */ public abstract class AbstractAsyncRequestConsumer implements HttpAsyncRequestConsumer { private final AtomicBoolean completed; private volatile T result; private volatile Exception ex; public AbstractAsyncRequestConsumer() { super(); this.completed = new AtomicBoolean(false); } /** * Invoked when a HTTP request message is received. Please note * that the {@link #onContentReceived(ContentDecoder, IOControl)} method * will be invoked only for if the request message implements * {@link HttpEntityEnclosingRequest} interface and has a content * entity enclosed. * * @param request HTTP request message. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ protected abstract void onRequestReceived( HttpRequest request) throws HttpException, IOException; /** * Invoked if the request message encloses a content entity. * * @param entity HTTP entity * @param contentType expected content type. * @throws IOException in case of an I/O error */ protected abstract void onEntityEnclosed( HttpEntity entity, ContentType contentType) throws IOException; /** * Invoked to process a chunk of content from the {@link ContentDecoder}. * The {@link IOControl} interface can be used to suspend input events * if the consumer is temporarily unable to consume more content. *

* The consumer can use the {@link ContentDecoder#isCompleted()} method * to find out whether or not the message content has been fully consumed. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. * @throws IOException in case of an I/O error */ protected abstract void onContentReceived( ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Invoked to generate a result object from the received HTTP request * message. * * @param context HTTP context. * @return result of the request processing. * @throws Exception in case of an abnormal termination. */ protected abstract T buildResult(HttpContext context) throws Exception; /** * Invoked to release all system resources currently allocated. */ protected abstract void releaseResources(); /** * Invoked when the consumer is being closed. * @throws IOException may be thrown by subclassses * * @since 4.3 */ protected void onClose() throws IOException { } /** * Use {@link #onRequestReceived(HttpRequest)} instead. */ @Override public final void requestReceived( final HttpRequest request) throws HttpException, IOException { onRequestReceived(request); if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { final ContentType contentType = ContentType.getOrDefault(entity); onEntityEnclosed(entity, contentType); } } } /** * Use {@link #onContentReceived(ContentDecoder, IOControl)} instead. */ @Override public final void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { onContentReceived(decoder, ioctrl); } /** * Use {@link #buildResult(HttpContext)} instead. */ @Override public final void requestCompleted(final HttpContext context) { if (this.completed.compareAndSet(false, true)) { try { this.result = buildResult(context); } catch (final Exception ex) { this.ex = ex; } finally { releaseResources(); } } } @Override public final void failed(final Exception ex) { if (this.completed.compareAndSet(false, true)) { this.ex = ex; releaseResources(); } } @Override public final void close() throws IOException { if (this.completed.compareAndSet(false, true)) { releaseResources(); onClose(); } } @Override public Exception getException() { return this.ex; } @Override public T getResult() { return this.result; } @Override public boolean isDone() { return this.completed.get(); } } ././@LongLink0100644 0000000 0000000 00000000162 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncResponseProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncResponse0100644 0000000 0000000 00000011274 12613456026 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.nio.protocol; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.EntityAsyncContentProducer; import org.apache.http.nio.entity.HttpAsyncContentProducer; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Args; /** * Basic implementation of {@link HttpAsyncResponseProducer}. The producer * can make use of the {@link HttpAsyncContentProducer} interface to * efficiently stream out message content to the underlying non-blocking HTTP * connection, if it is implemented by the {@link HttpEntity} inclosed in * the response. * * @see HttpAsyncContentProducer * * @since 4.2 */ public class BasicAsyncResponseProducer implements HttpAsyncResponseProducer { private final HttpResponse response; private final HttpAsyncContentProducer producer; /** * Creates a producer that can be used to transmit the given response * message. The given content producer will be used to stream out message * content. Please note that the response message is expected to enclose * an {@link HttpEntity} whose properties are consistent with the behavior * of the content producer. * * @param response response message. * @param producer response content producer. */ protected BasicAsyncResponseProducer( final HttpResponse response, final HttpAsyncContentProducer producer) { super(); Args.notNull(response, "HTTP response"); Args.notNull(producer, "HTTP content producer"); this.response = response; this.producer = producer; } /** * Creates a producer that can be used to transmit the given response * message. If the response message encloses an {@link HttpEntity} * it is also expected to implement {@link HttpAsyncContentProducer}. * * @param response response message. */ public BasicAsyncResponseProducer(final HttpResponse response) { super(); Args.notNull(response, "HTTP response"); this.response = response; final HttpEntity entity = response.getEntity(); if (entity != null) { if (entity instanceof HttpAsyncContentProducer) { this.producer = (HttpAsyncContentProducer) entity; } else { this.producer = new EntityAsyncContentProducer(entity); } } else { this.producer = null; } } @Override public HttpResponse generateResponse() { return this.response; } @Override public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { if (this.producer != null) { this.producer.produceContent(encoder, ioctrl); if (encoder.isCompleted()) { this.producer.close(); } } } @Override public void responseCompleted(final HttpContext context) { } @Override public void failed(final Exception ex) { } @Override public void close() throws IOException { if (this.producer != null) { this.producer.close(); } } @Override public String toString() { final StringBuilder buf = new StringBuilder(); buf.append(this.response); if (this.producer != null) { buf.append(" ").append(this.producer); } return buf.toString(); } } ././@LongLink0100644 0000000 0000000 00000000162 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncResponseConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncResponse0100644 0000000 0000000 00000006457 12613456026 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.nio.protocol; import java.io.IOException; import org.apache.http.ContentTooLongException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.entity.ContentType; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.ContentBufferEntity; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.nio.util.SimpleInputBuffer; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Asserts; /** * Basic implementation of {@link HttpAsyncResponseConsumer}. Please note that * this consumer buffers response content in memory and should be used for * relatively small response messages. * * @since 4.2 */ public class BasicAsyncResponseConsumer extends AbstractAsyncResponseConsumer { private volatile HttpResponse response; private volatile SimpleInputBuffer buf; public BasicAsyncResponseConsumer() { super(); } @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; } @Override protected void onEntityEnclosed( final HttpEntity entity, final ContentType contentType) throws IOException { long len = entity.getContentLength(); if (len > Integer.MAX_VALUE) { throw new ContentTooLongException("Entity content is too long: " + len); } if (len < 0) { len = 4096; } this.buf = new SimpleInputBuffer((int) len, new HeapByteBufferAllocator()); this.response.setEntity(new ContentBufferEntity(entity, this.buf)); } @Override protected void onContentReceived( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { Asserts.notNull(this.buf, "Content buffer"); this.buf.consumeContent(decoder); } @Override protected void releaseResources() { this.response = null; this.buf = null; } @Override protected HttpResponse buildResult(final HttpContext context) { return this.response; } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/MessageState.java0100644 0000000 0000000 00000002425 12613456026 032211 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; enum MessageState { READY, INIT, ACK_EXPECTED, BODY_STREAM, COMPLETED } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/package-info.java0100644 0000000 0000000 00000002505 12613456026 032147 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 asynchronous, event driven communication. */ package org.apache.http.nio.protocol; ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestPr0100644 0000000 0000000 00000011227 12613456026 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.nio.protocol; import java.io.Closeable; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; /** * {@code HttpAsyncRequestProducer} is a callback interface whose methods * get invoked to generate an HTTP request message and to stream message * content to a non-blocking 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 {@link #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. * * @since 4.2 */ public interface HttpAsyncRequestProducer extends Closeable { /** * Invoked to obtain the request target host. */ HttpHost getTarget(); /** * Invoked to generate a HTTP request message head. The message is expected * to implement the {@link org.apache.http.HttpEntityEnclosingRequest} interface * if it is to enclose a content entity. The {@link #produceContent( * ContentEncoder, IOControl)} method will not be invoked if * {@link org.apache.http.HttpEntityEnclosingRequest#getEntity()} * returns {@code null}. * * @return HTTP request message. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ HttpRequest generateRequest() throws IOException, HttpException; /** * Invoked to write out a chunk of content to the {@link ContentEncoder}. * The {@link IOControl} interface can be used to suspend output event * notifications if the producer is temporarily unable to produce more content. *

* When all content is finished, the producer MUST call * {@link ContentEncoder#complete()}. Failure to do so may cause the entity * to be incorrectly delimited. *

* Please note that the {@link ContentEncoder} object is not thread-safe and * should only be used within the context of this method call. * The {@link IOControl} object can be shared and used on other thread * to resume output event notifications when more content is made available. * * @param encoder content encoder. * @param ioctrl I/O control of the underlying connection. * @throws IOException in case of an I/O error */ void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException; /** * Invoked to signal that the request has been fully written out. * * @param context HTTP context */ void requestCompleted(HttpContext context); /** * Invoked to signal that the response processing terminated abnormally. * * @param ex exception */ void failed(Exception ex); /** * Determines whether or not this producer is capable of producing * HTTP request messages more than once. */ boolean isRepeatable(); /** * 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. * * @throws IOException in case of an I/O error */ void resetRequest() throws IOException; } ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncResponseProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncResponseP0100644 0000000 0000000 00000006263 12613456026 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.nio.protocol; import java.io.Closeable; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; /** * {@code HttpAsyncResponseProducer} is a callback interface whose methods * get invoked to generate an HTTP response message and to stream message * content to a non-blocking HTTP connection on the server side. * * @since 4.2 */ public interface HttpAsyncResponseProducer extends Closeable { /** * Invoked to generate a HTTP response message head. * * @return HTTP response message. */ HttpResponse generateResponse(); /** * Invoked to write out a chunk of content to the {@link ContentEncoder}. * The {@link IOControl} interface can be used to suspend output event * notifications if the producer is temporarily unable to produce more content. *

* When all content is finished, the producer MUST call * {@link ContentEncoder#complete()}. Failure to do so may cause the entity * to be incorrectly delimited. *

* Please note that the {@link ContentEncoder} object is not thread-safe and * should only be used within the context of this method call. * The {@link IOControl} object can be shared and used on other thread * to resume output event notifications when more content is made available. * * @param encoder content encoder. * @param ioctrl I/O control of the underlying connection. * @throws IOException in case of an I/O error */ void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException; /** * Invoked to signal that the response has been fully written out. * * @param context HTTP context */ void responseCompleted(HttpContext context); /** * Invoked to signal that the response processing terminated abnormally. * * @param ex exception */ void failed(Exception ex); } ././@LongLink0100644 0000000 0000000 00000000155 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/ErrorResponseProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/ErrorResponseProdu0100644 0000000 0000000 00000006112 12613456026 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.nio.protocol; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.EntityAsyncContentProducer; import org.apache.http.nio.entity.HttpAsyncContentProducer; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; class ErrorResponseProducer implements HttpAsyncResponseProducer { private final HttpResponse response; private final HttpEntity entity; private final HttpAsyncContentProducer contentProducer; private final boolean keepAlive; ErrorResponseProducer( final HttpResponse response, final HttpEntity entity, final boolean keepAlive) { super(); this.response = response; this.entity = entity; if (entity instanceof HttpAsyncContentProducer) { this.contentProducer = (HttpAsyncContentProducer) entity; } else { this.contentProducer = new EntityAsyncContentProducer(entity); } this.keepAlive = keepAlive; } @Override public HttpResponse generateResponse() { if (this.keepAlive) { response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); } else { response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); } response.setEntity(this.entity); return response; } @Override public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { this.contentProducer.produceContent(encoder, ioctrl); } @Override public void responseCompleted(final HttpContext context) { } @Override public void failed(final Exception ex) { } @Override public void close() throws IOException { this.contentProducer.close(); } } ././@LongLink0100644 0000000 0000000 00000000157 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestHa0100644 0000000 0000000 00000007374 12613456026 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.nio.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.protocol.HttpContext; /** * {@code 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. * * @since 4.2 */ public interface HttpAsyncRequestHandler { /** * Triggered when an incoming request is received. This method should * return a {@link HttpAsyncRequestConsumer} that will be used to process * the request and consume message content if enclosed. The consumer * can optionally parse or transform the message content into a structured * object which is then passed onto * the {@link #handle(Object, HttpAsyncExchange, HttpContext)} * method for further processing. * * @param request the entity enclosing request. * @param context the execution context. * @return request consumer. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ HttpAsyncRequestConsumer processRequest( HttpRequest request, HttpContext context) throws HttpException, IOException; /** * Triggered to complete request processing and to initiate the process of * generating a response. This method does not have to submit a response * immediately. It can defer transmission of an HTTP response back to * the client without blocking the I/O thread by delegating the process * of request handling to another service or a worker thread. HTTP response * can be submitted as a later a later point of time using * {@link HttpAsyncExchange} once response content becomes available. * * @param data request data returned by the request consumer. * @param httpExchange HTTP exchange. * @param context 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( T data, HttpAsyncExchange httpExchange, HttpContext context) throws HttpException, IOException; } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/PipeliningClientExchangeHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/PipeliningClientEx0100644 0000000 0000000 00000031453 12613456026 032441 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.concurrent.BasicFuture; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * Pipelining implementation of {@link org.apache.http.nio.protocol.HttpAsyncClientExchangeHandler} * that executes a series of pipelined HTTP requests. * * @param the result type of request execution. * @since 4.4 */ @Pipelined() public class PipeliningClientExchangeHandler implements HttpAsyncClientExchangeHandler { private final Queue requestProducerQueue; private final Queue> responseConsumerQueue; private final Queue requestQueue; private final Queue resultQueue; private final BasicFuture> future; private final HttpContext localContext; private final NHttpClientConnection conn; private final HttpProcessor httppocessor; private final ConnectionReuseStrategy connReuseStrategy; private final AtomicReference requestProducerRef; private final AtomicReference> responseConsumerRef; private final AtomicBoolean keepAlive; private final AtomicBoolean closed; /** * Creates new instance of {@code PipeliningClientExchangeHandler}. * * @param requestProducers the request producers. * @param responseConsumers the response consumers. * @param callback the future callback invoked when the operation is completed. * @param localContext the local execution context. * @param conn the actual connection. * @param httppocessor the HTTP protocol processor. * @param connReuseStrategy the connection re-use strategy. */ public PipeliningClientExchangeHandler( final List requestProducers, final List> responseConsumers, final FutureCallback> callback, final HttpContext localContext, final NHttpClientConnection conn, final HttpProcessor httppocessor, final ConnectionReuseStrategy connReuseStrategy) { super(); Args.notEmpty(requestProducers, "Request producer list"); Args.notEmpty(responseConsumers, "Response consumer list"); Args.check(requestProducers.size() == responseConsumers.size(), "Number of request producers does not match that of response consumers"); this.requestProducerQueue = new ConcurrentLinkedQueue(requestProducers); this.responseConsumerQueue = new ConcurrentLinkedQueue>(responseConsumers); this.requestQueue = new ConcurrentLinkedQueue(); this.resultQueue = new ConcurrentLinkedQueue(); this.future = new BasicFuture>(callback); this.localContext = Args.notNull(localContext, "HTTP context"); this.conn = Args.notNull(conn, "HTTP connection"); this.httppocessor = Args.notNull(httppocessor, "HTTP processor"); this.connReuseStrategy = connReuseStrategy != null ? connReuseStrategy : DefaultConnectionReuseStrategy.INSTANCE; this.localContext.setAttribute(HttpCoreContext.HTTP_CONNECTION, this.conn); this.requestProducerRef = new AtomicReference(null); this.responseConsumerRef = new AtomicReference>(null); this.keepAlive = new AtomicBoolean(false); this.closed = new AtomicBoolean(false); } /** * Creates new instance of {@code PipeliningClientExchangeHandler}. * * @param requestProducers the request producers. * @param responseConsumers the response consumers. * @param localContext the local execution context. * @param conn the actual connection. * @param httppocessor the HTTP protocol processor. */ public PipeliningClientExchangeHandler( final List requestProducers, final List> responseConsumers, final HttpContext localContext, final NHttpClientConnection conn, final HttpProcessor httppocessor) { this(requestProducers, responseConsumers, null, localContext, conn, httppocessor, null); } public Future> getFuture() { return this.future; } private static void closeQuietly(final Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (final IOException ex) { } } } private void releaseResources() { closeQuietly(this.requestProducerRef.getAndSet(null)); closeQuietly(this.responseConsumerRef.getAndSet(null)); while (!this.requestProducerQueue.isEmpty()) { closeQuietly(this.requestProducerQueue.remove()); } while (!this.responseConsumerQueue.isEmpty()) { closeQuietly(this.responseConsumerQueue.remove()); } this.requestQueue.clear(); this.resultQueue.clear(); } @Override public void close() throws IOException { if (this.closed.compareAndSet(false, true)) { releaseResources(); if (!this.future.isDone()) { this.future.cancel(); } } } @Override public HttpRequest generateRequest() throws IOException, HttpException { Asserts.check(this.requestProducerRef.get() == null, "Inconsistent state: request producer is not null"); final HttpAsyncRequestProducer requestProducer = this.requestProducerQueue.poll(); if (requestProducer == null) { return null; } this.requestProducerRef.set(requestProducer); final HttpRequest request = requestProducer.generateRequest(); this.httppocessor.process(request, this.localContext); this.requestQueue.add(request); return request; } @Override public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { final HttpAsyncRequestProducer requestProducer = this.requestProducerRef.get(); Asserts.check(requestProducer != null, "Inconsistent state: request producer is null"); requestProducer.produceContent(encoder, ioctrl); } @Override public void requestCompleted() { final HttpAsyncRequestProducer requestProducer = this.requestProducerRef.getAndSet(null); Asserts.check(requestProducer != null, "Inconsistent state: request producer is null"); requestProducer.requestCompleted(this.localContext); } @Override public void responseReceived(final HttpResponse response) throws IOException, HttpException { Asserts.check(this.responseConsumerRef.get() == null, "Inconsistent state: response consumer is not null"); final HttpAsyncResponseConsumer responseConsumer = this.responseConsumerQueue.poll(); Asserts.check(responseConsumer != null, "Inconsistent state: response consumer queue is empty"); this.responseConsumerRef.set(responseConsumer); final HttpRequest request = this.requestQueue.poll(); Asserts.check(request != null, "Inconsistent state: request queue is empty"); this.localContext.setAttribute(HttpCoreContext.HTTP_REQUEST, request); this.localContext.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); this.httppocessor.process(response, this.localContext); responseConsumer.responseReceived(response); this.keepAlive.set(this.connReuseStrategy.keepAlive(response, this.localContext)); } @Override public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { final HttpAsyncResponseConsumer responseConsumer = this.responseConsumerRef.get(); Asserts.check(responseConsumer != null, "Inconsistent state: response consumer is null"); responseConsumer.consumeContent(decoder, ioctrl); } @Override public void responseCompleted() throws IOException { final HttpAsyncResponseConsumer responseConsumer = this.responseConsumerRef.getAndSet(null); Asserts.check(responseConsumer != null, "Inconsistent state: response consumer is null"); try { if (!this.keepAlive.get()) { this.conn.close(); } responseConsumer.responseCompleted(this.localContext); final T result = responseConsumer.getResult(); final Exception ex = responseConsumer.getException(); if (result != null) { this.resultQueue.add(result); } else { this.future.failed(ex); this.conn.shutdown(); } if (!conn.isOpen()) { if (this.closed.compareAndSet(false, true)) { releaseResources(); } } if (!this.future.isDone() && this.responseConsumerQueue.isEmpty()) { this.future.completed(new ArrayList(this.resultQueue)); this.resultQueue.clear(); } } catch (final RuntimeException ex) { failed(ex); throw ex; } } @Override public void inputTerminated() { failed(new ConnectionClosedException("Connection closed")); } @Override public void failed(final Exception ex) { if (this.closed.compareAndSet(false, true)) { try { final HttpAsyncRequestProducer requestProducer = this.requestProducerRef.get(); if (requestProducer != null) { requestProducer.failed(ex); } final HttpAsyncResponseConsumer responseConsumer = this.responseConsumerRef.get(); if (responseConsumer != null) { responseConsumer.failed(ex); } } finally { try { this.future.failed(ex); } finally { releaseResources(); } } } } @Override public boolean cancel() { if (this.closed.compareAndSet(false, true)) { try { try { final HttpAsyncResponseConsumer responseConsumer = this.responseConsumerRef.get(); return responseConsumer != null && responseConsumer.cancel(); } finally { this.future.cancel(); } } finally { releaseResources(); } } return false; } @Override public boolean isDone() { return this.future.isDone(); } } ././@LongLink0100644 0000000 0000000 00000000170 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/UriHttpAsyncRequestHandlerMapper.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/UriHttpAsyncReques0100644 0000000 0000000 00000007426 12613456026 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.nio.protocol; import org.apache.http.HttpRequest; import org.apache.http.annotation.ThreadSafe; import org.apache.http.protocol.UriPatternMatcher; import org.apache.http.util.Args; /** * Maintains a map of HTTP request handlers keyed by a request URI pattern. *
* Patterns may have three formats: *

    *
  • {@code *}
  • *
  • {@code *<uri>}
  • *
  • {@code <uri>*}
  • *
*
* This class can be used to map an instance of {@link HttpAsyncRequestHandler} * 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 public class UriHttpAsyncRequestHandlerMapper implements HttpAsyncRequestHandlerMapper { private final UriPatternMatcher> matcher; protected UriHttpAsyncRequestHandlerMapper(final UriPatternMatcher> matcher) { super(); this.matcher = Args.notNull(matcher, "Pattern matcher"); } public UriHttpAsyncRequestHandlerMapper() { this(new UriPatternMatcher>()); } /** * Registers the given {@link HttpAsyncRequestHandler} 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 HttpAsyncRequestHandler handler) { matcher.register(pattern, handler); } /** * Removes registered handler, if exists, for the given pattern. * * @param pattern the pattern to unregister the handler for. */ public void unregister(final String pattern) { matcher.unregister(pattern); } /** * Extracts request path from the given {@link HttpRequest} */ protected String getRequestPath(final HttpRequest request) { String uriPath = request.getRequestLine().getUri(); int index = uriPath.indexOf("?"); if (index != -1) { uriPath = uriPath.substring(0, index); } else { index = uriPath.indexOf("#"); if (index != -1) { uriPath = uriPath.substring(0, index); } } return uriPath; } /** * Looks up a handler matching the given request URI. * * @param request the request * @return handler or {@code null} if no match is found. */ @Override public HttpAsyncRequestHandler lookup(final HttpRequest request) { return matcher.lookup(getRequestPath(request)); } } ././@LongLink0100644 0000000 0000000 00000000153 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NullRequestConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NullRequestConsume0100644 0000000 0000000 00000005121 12613456026 032515 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.http.HttpRequest; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; class NullRequestConsumer implements HttpAsyncRequestConsumer { private final ByteBuffer buffer; private volatile boolean completed; NullRequestConsumer() { super(); this.buffer = ByteBuffer.allocate(2048); } @Override public void requestReceived(final HttpRequest request) { } @Override public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { int lastRead; do { this.buffer.clear(); lastRead = decoder.read(this.buffer); } while (lastRead > 0); } @Override public void requestCompleted(final HttpContext context) { this.completed = true; } @Override public void failed(final Exception ex) { this.completed = true; } @Override public Object getResult() { return Boolean.valueOf(this.completed); } @Override public Exception getException() { return null; } @Override public void close() throws IOException { this.completed = true; } @Override public boolean isDone() { return this.completed; } } ././@LongLink0100644 0000000 0000000 00000000150 12613460517 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncService.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncService.j0100644 0000000 0000000 00000120573 12613456026 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.nio.protocol; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.ExceptionLogger; 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.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.concurrent.Cancellable; import org.apache.http.entity.ContentType; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServerEventHandler; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.reactor.SessionBufferStatus; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * {@code HttpAsyncService} is a fully asynchronous HTTP server side protocol * handler based on the non-blocking (NIO) I/O model. * {@code HttpAsyncServerProtocolHandler} translates individual events fired * through the {@link NHttpServerEventHandler} interface into logically related * HTTP message exchanges. *

* Upon receiving an incoming request {@code HttpAsyncService} verifies * the message for compliance with the server expectations using * {@link HttpAsyncExpectationVerifier}, if provided, and then * {@link HttpAsyncRequestHandlerMapper} is used to map the request * to a particular {@link HttpAsyncRequestHandler} intended to handle * the request with the given URI. The protocol handler uses the selected * {@link HttpAsyncRequestHandler} instance to process the incoming request * and to generate an outgoing response. *

* {@code HttpAsyncService} 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 HttpAsyncRequestHandler}s are expected * to implement application specific content generation and processing. *

* Individual {@link HttpAsyncRequestHandler}s do not have to submit a response * immediately. They can defer transmission of an HTTP response back to * the client without blocking the I/O thread by delegating the process of * request handling to another service or a worker thread. HTTP response can * be submitted as a later a later point of time once response content becomes * available. * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable // provided injected dependencies are immutable public class HttpAsyncService implements NHttpServerEventHandler { static final String HTTP_EXCHANGE_STATE = "http.nio.http-exchange-state"; private final HttpProcessor httpProcessor; private final ConnectionReuseStrategy connStrategy; private final HttpResponseFactory responseFactory; private final HttpAsyncRequestHandlerMapper handlerMapper; private final HttpAsyncExpectationVerifier expectationVerifier; private final ExceptionLogger exceptionLogger; /** * Creates new instance of {@code HttpAsyncServerProtocolHandler}. * * @param httpProcessor HTTP protocol processor (required). * @param connStrategy Connection re-use strategy (required). * @param responseFactory HTTP response factory (required). * @param handlerResolver Request handler resolver. * @param expectationVerifier Request expectation verifier (optional). * @param params HTTP parameters (required). * * @deprecated (4.3) use {@link HttpAsyncService#HttpAsyncService(HttpProcessor, * ConnectionReuseStrategy, HttpResponseFactory, HttpAsyncRequestHandlerMapper, * HttpAsyncExpectationVerifier)} */ @Deprecated public HttpAsyncService( final HttpProcessor httpProcessor, final ConnectionReuseStrategy connStrategy, final HttpResponseFactory responseFactory, final HttpAsyncRequestHandlerResolver handlerResolver, final HttpAsyncExpectationVerifier expectationVerifier, final HttpParams params) { this(httpProcessor, connStrategy, responseFactory, new HttpAsyncRequestHandlerResolverAdapter(handlerResolver), expectationVerifier); } /** * Creates new instance of {@code HttpAsyncServerProtocolHandler}. * * @param httpProcessor HTTP protocol processor (required). * @param connStrategy Connection re-use strategy (required). * @param handlerResolver Request handler resolver. * @param params HTTP parameters (required). * * @deprecated (4.3) use {@link HttpAsyncService#HttpAsyncService(HttpProcessor, * ConnectionReuseStrategy, HttpResponseFactory, HttpAsyncRequestHandlerMapper, * HttpAsyncExpectationVerifier)} */ @Deprecated public HttpAsyncService( final HttpProcessor httpProcessor, final ConnectionReuseStrategy connStrategy, final HttpAsyncRequestHandlerResolver handlerResolver, final HttpParams params) { this(httpProcessor, connStrategy, DefaultHttpResponseFactory.INSTANCE, new HttpAsyncRequestHandlerResolverAdapter(handlerResolver), null); } /** * Creates new instance of {@code HttpAsyncServerProtocolHandler}. * * @param httpProcessor HTTP protocol processor. * @param connStrategy Connection re-use strategy. If {@code null} * {@link DefaultConnectionReuseStrategy#INSTANCE} will be used. * @param responseFactory HTTP response factory. If {@code null} * {@link DefaultHttpResponseFactory#INSTANCE} will be used. * @param handlerMapper Request handler mapper. * @param expectationVerifier Request expectation verifier. May be {@code null}. * * @since 4.3 */ public HttpAsyncService( final HttpProcessor httpProcessor, final ConnectionReuseStrategy connStrategy, final HttpResponseFactory responseFactory, final HttpAsyncRequestHandlerMapper handlerMapper, final HttpAsyncExpectationVerifier expectationVerifier) { this(httpProcessor, connStrategy, responseFactory, handlerMapper, expectationVerifier, null); } /** * Creates new instance of {@code HttpAsyncServerProtocolHandler}. * * @param httpProcessor HTTP protocol processor. * @param connStrategy Connection re-use strategy. If {@code null} * {@link DefaultConnectionReuseStrategy#INSTANCE} will be used. * @param responseFactory HTTP response factory. If {@code null} * {@link DefaultHttpResponseFactory#INSTANCE} will be used. * @param handlerMapper Request handler mapper. * @param expectationVerifier Request expectation verifier. May be {@code null}. * @param exceptionLogger Exception logger. If {@code null} * {@link ExceptionLogger#NO_OP} will be used. Please note that the exception * logger will be only used to log I/O exception thrown while closing * {@link java.io.Closeable} objects (such as {@link org.apache.http.HttpConnection}). * * @since 4.4 */ public HttpAsyncService( final HttpProcessor httpProcessor, final ConnectionReuseStrategy connStrategy, final HttpResponseFactory responseFactory, final HttpAsyncRequestHandlerMapper handlerMapper, final HttpAsyncExpectationVerifier expectationVerifier, final ExceptionLogger exceptionLogger) { super(); this.httpProcessor = Args.notNull(httpProcessor, "HTTP processor"); this.connStrategy = connStrategy != null ? connStrategy : DefaultConnectionReuseStrategy.INSTANCE; this.responseFactory = responseFactory != null ? responseFactory : DefaultHttpResponseFactory.INSTANCE; this.handlerMapper = handlerMapper; this.expectationVerifier = expectationVerifier; this.exceptionLogger = exceptionLogger != null ? exceptionLogger : ExceptionLogger.NO_OP; } /** * Creates new instance of {@code HttpAsyncServerProtocolHandler}. * * @param httpProcessor HTTP protocol processor. * @param handlerMapper Request handler mapper. * * @since 4.3 */ public HttpAsyncService( final HttpProcessor httpProcessor, final HttpAsyncRequestHandlerMapper handlerMapper) { this(httpProcessor, null, null, handlerMapper, null); } /** * Creates new instance of {@code HttpAsyncServerProtocolHandler}. * * @param httpProcessor HTTP protocol processor. * @param handlerMapper Request handler mapper. * @param exceptionLogger Exception logger. If {@code null} * {@link ExceptionLogger#NO_OP} will be used. Please note that the exception * logger will be only used to log I/O exception thrown while closing * {@link java.io.Closeable} objects (such as {@link org.apache.http.HttpConnection}). * * @since 4.4 */ public HttpAsyncService( final HttpProcessor httpProcessor, final HttpAsyncRequestHandlerMapper handlerMapper, final ExceptionLogger exceptionLogger) { this(httpProcessor, null, null, handlerMapper, null, exceptionLogger); } @Override public void connected(final NHttpServerConnection conn) { final State state = new State(); conn.getContext().setAttribute(HTTP_EXCHANGE_STATE, state); } @Override public void closed(final NHttpServerConnection conn) { final State state = (State) conn.getContext().removeAttribute(HTTP_EXCHANGE_STATE); if (state != null) { state.setTerminated(); closeHandlers(state); final Cancellable cancellable = state.getCancellable(); if (cancellable != null) { cancellable.cancel(); } } } @Override public void exception( final NHttpServerConnection conn, final Exception cause) { final State state = getState(conn); if (state == null) { shutdownConnection(conn); log(cause); return; } state.setTerminated(); closeHandlers(state, cause); final Cancellable cancellable = state.getCancellable(); if (cancellable != null) { cancellable.cancel(); } final Queue pipeline = state.getPipeline(); if (!pipeline.isEmpty() || conn.isResponseSubmitted() || state.getResponseState().compareTo(MessageState.INIT) > 0) { // There is not much that we can do if a response // has already been submitted or pipelining is being used. shutdownConnection(conn); } else { try { final Incoming incoming = state.getIncoming(); final HttpRequest request = incoming != null ? incoming.getRequest() : null; final HttpContext context = incoming != null ? incoming.getContext() : new BasicHttpContext(); final HttpAsyncResponseProducer responseProducer = handleException(cause, context); final HttpResponse response = responseProducer.generateResponse(); final Outgoing outgoing = new Outgoing(request, response, responseProducer, context); state.setResponseState(MessageState.INIT); state.setOutgoing(outgoing); commitFinalResponse(conn, state); } catch (final Exception ex) { shutdownConnection(conn); closeHandlers(state); if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { log(ex); } } } } @Override public void requestReceived( final NHttpServerConnection conn) throws IOException, HttpException { final State state = getState(conn); Asserts.notNull(state, "Connection state"); Asserts.check(state.getRequestState() == MessageState.READY, "Unexpected request state %s", state.getRequestState()); final HttpRequest request = conn.getHttpRequest(); final HttpContext context = new BasicHttpContext(); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); this.httpProcessor.process(request, context); final HttpAsyncRequestHandler requestHandler = getRequestHandler(request); final HttpAsyncRequestConsumer consumer = requestHandler.processRequest(request, context); consumer.requestReceived(request); final Incoming incoming = new Incoming(request, requestHandler, consumer, context); state.setIncoming(incoming); if (request instanceof HttpEntityEnclosingRequest) { // If 100-continue is expected make sure // there is no pending response data, no pipelined requests or buffered input if (((HttpEntityEnclosingRequest) request).expectContinue() && state.getResponseState() == MessageState.READY && state.getPipeline().isEmpty() && !(conn instanceof SessionBufferStatus && ((SessionBufferStatus) conn).hasBufferedInput())) { state.setRequestState(MessageState.ACK_EXPECTED); final HttpResponse ack = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_CONTINUE, context); if (this.expectationVerifier != null) { conn.suspendInput(); conn.suspendOutput(); final HttpAsyncExchange httpAsyncExchange = new HttpAsyncExchangeImpl( request, ack, state, conn, context); this.expectationVerifier.verify(httpAsyncExchange, context); } else { conn.submitResponse(ack); state.setRequestState(MessageState.BODY_STREAM); } } else { state.setRequestState(MessageState.BODY_STREAM); } } else { // No request content is expected. Process request right away completeRequest(incoming, conn, state); } } @Override public void inputReady( final NHttpServerConnection conn, final ContentDecoder decoder) throws IOException, HttpException { final State state = getState(conn); Asserts.notNull(state, "Connection state"); Asserts.check(state.getRequestState() == MessageState.BODY_STREAM, "Unexpected request state %s", state.getRequestState()); final Incoming incoming = state.getIncoming(); Asserts.notNull(incoming, "Incoming request"); final HttpAsyncRequestConsumer consumer = incoming.getConsumer(); consumer.consumeContent(decoder, conn); if (decoder.isCompleted()) { completeRequest(incoming, conn, state); } } @Override public void responseReady( final NHttpServerConnection conn) throws IOException, HttpException { final State state = getState(conn); Asserts.notNull(state, "Connection state"); Asserts.check(state.getResponseState() == MessageState.READY || state.getResponseState() == MessageState.INIT, "Unexpected response state %s", state.getResponseState()); if (state.getRequestState() == MessageState.ACK_EXPECTED) { final Outgoing outgoing = state.getOutgoing(); Asserts.notNull(outgoing, "Outgoing response"); final HttpResponse response = outgoing.getResponse(); final int status = response.getStatusLine().getStatusCode(); if (status == 100) { final HttpContext context = outgoing.getContext(); final HttpAsyncResponseProducer responseProducer = outgoing.getProducer(); try { // Make sure 100 response has no entity response.setEntity(null); conn.requestInput(); state.setRequestState(MessageState.BODY_STREAM); state.setOutgoing(null); conn.submitResponse(response); responseProducer.responseCompleted(context); } finally { responseProducer.close(); } } else if (status >= 400) { conn.resetInput(); state.setRequestState(MessageState.READY); commitFinalResponse(conn, state); } else { throw new HttpException("Invalid response: " + response.getStatusLine()); } } else { if (state.getResponseState() == MessageState.READY) { final Queue pipeline = state.getPipeline(); final PipelineEntry pipelineEntry = pipeline.poll(); if (pipelineEntry == null) { conn.suspendOutput(); return; } state.setResponseState(MessageState.INIT); final Object result = pipelineEntry.getResult(); final HttpRequest request = pipelineEntry.getRequest(); final HttpContext context = pipelineEntry.getContext(); if (result != null) { final HttpResponse response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, context); final HttpAsyncExchangeImpl httpExchange = new HttpAsyncExchangeImpl( request, response, state, conn, context); final HttpAsyncRequestHandler handler = pipelineEntry.getHandler(); conn.suspendOutput(); try { handler.handle(result, httpExchange, context); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { pipeline.add(new PipelineEntry( request, null, ex, handler, context)); state.setResponseState(MessageState.READY); responseReady(conn); return; } } else { final Exception exception = pipelineEntry.getException(); final HttpAsyncResponseProducer responseProducer = handleException( exception != null ? exception : new HttpException("Internal error processing request"), context); final HttpResponse error = responseProducer.generateResponse(); state.setOutgoing(new Outgoing(request, error, responseProducer, context)); } } if (state.getResponseState() == MessageState.INIT) { final Outgoing outgoing; synchronized (state) { outgoing = state.getOutgoing(); if (outgoing == null) { conn.suspendOutput(); return; } } final HttpResponse response = outgoing.getResponse(); final int status = response.getStatusLine().getStatusCode(); if (status >= 200) { commitFinalResponse(conn, state); } else { throw new HttpException("Invalid response: " + response.getStatusLine()); } } } } @Override public void outputReady( final NHttpServerConnection conn, final ContentEncoder encoder) throws HttpException, IOException { final State state = getState(conn); Asserts.notNull(state, "Connection state"); Asserts.check(state.getResponseState() == MessageState.BODY_STREAM, "Unexpected response state %s", state.getResponseState()); final Outgoing outgoing = state.getOutgoing(); Asserts.notNull(outgoing, "Outgoing response"); final HttpAsyncResponseProducer responseProducer = outgoing.getProducer(); responseProducer.produceContent(encoder, conn); if (encoder.isCompleted()) { completeResponse(outgoing, conn, state); } } @Override public void endOfInput(final NHttpServerConnection conn) throws IOException { // Closing connection in an orderly manner and // waiting for output buffer to get flushed. // Do not want to wait indefinitely, though, in case // the opposite end is not reading if (conn.getSocketTimeout() <= 0) { conn.setSocketTimeout(1000); } conn.close(); } @Override public void timeout(final NHttpServerConnection conn) throws IOException { final State state = getState(conn); if (state != null) { closeHandlers(state, new SocketTimeoutException()); } if (conn.getStatus() == NHttpConnection.ACTIVE) { conn.close(); if (conn.getStatus() == NHttpConnection.CLOSING) { // Give the connection some grace time to // close itself nicely conn.setSocketTimeout(250); } } else { conn.shutdown(); } } private State getState(final NHttpConnection conn) { return (State) conn.getContext().getAttribute(HTTP_EXCHANGE_STATE); } /** * This method can be used to log I/O exception thrown while closing * {@link java.io.Closeable} objects (such as * {@link org.apache.http.HttpConnection}). * * @param ex I/O exception thrown by {@link java.io.Closeable#close()} */ protected void log(final Exception ex) { this.exceptionLogger.log(ex); } private void shutdownConnection(final NHttpConnection conn) { try { conn.shutdown(); } catch (final IOException ex) { log(ex); } } private void closeHandlers(final State state, final Exception ex) { final HttpAsyncRequestConsumer consumer = state.getIncoming() != null ? state.getIncoming().getConsumer() : null; if (consumer != null) { try { consumer.failed(ex); } finally { try { consumer.close(); } catch (final IOException ioex) { log(ioex); } } } final HttpAsyncResponseProducer producer = state.getOutgoing() != null ? state.getOutgoing().getProducer() : null; if (producer != null) { try { producer.failed(ex); } finally { try { producer.close(); } catch (final IOException ioex) { log(ioex); } } } } private void closeHandlers(final State state) { final HttpAsyncRequestConsumer consumer = state.getIncoming() != null ? state.getIncoming().getConsumer() : null; if (consumer != null) { try { consumer.close(); } catch (final IOException ioex) { log(ioex); } } final HttpAsyncResponseProducer producer = state.getOutgoing() != null ? state.getOutgoing().getProducer() : null; if (producer != null) { try { producer.close(); } catch (final IOException ioex) { log(ioex); } } } protected HttpAsyncResponseProducer handleException( final Exception ex, final HttpContext context) { final int code; if (ex instanceof MethodNotSupportedException) { code = HttpStatus.SC_NOT_IMPLEMENTED; } else if (ex instanceof UnsupportedHttpVersionException) { code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED; } else if (ex instanceof ProtocolException) { code = HttpStatus.SC_BAD_REQUEST; } else { code = HttpStatus.SC_INTERNAL_SERVER_ERROR; } String message = ex.getMessage(); if (message == null) { message = ex.toString(); } final HttpResponse response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, code, context); return new ErrorResponseProducer(response, new NStringEntity(message, ContentType.DEFAULT_TEXT), false); } /** * This method can be used to handle callback set up happened after * response submission. * * @param cancellable Request cancellation callback. * @param context Request context. * * @since 4.4 */ protected void handleAlreadySubmittedResponse( final Cancellable cancellable, final HttpContext context) { throw new IllegalStateException("Response already submitted"); } /** * This method can be used to handle double response submission. * * @param responseProducer Response producer for second response. * @param context Request context. * * @since 4.4 */ protected void handleAlreadySubmittedResponse( final HttpAsyncResponseProducer responseProducer, final HttpContext context) { throw new IllegalStateException("Response already submitted"); } private boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) { if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { return false; } final int status = response.getStatusLine().getStatusCode(); return status >= HttpStatus.SC_OK && status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT; } private void completeRequest( final Incoming incoming, final NHttpServerConnection conn, final State state) throws IOException, HttpException { state.setRequestState(MessageState.READY); state.setIncoming(null); final PipelineEntry pipelineEntry; final HttpAsyncRequestConsumer consumer = incoming.getConsumer(); try { final HttpContext context = incoming.getContext(); consumer.requestCompleted(context); pipelineEntry = new PipelineEntry( incoming.getRequest(), consumer.getResult(), consumer.getException(), incoming.getHandler(), context); } finally { consumer.close(); } final Queue pipeline = state.getPipeline(); pipeline.add(pipelineEntry); if (state.getResponseState() == MessageState.READY) { conn.requestOutput(); } } private void commitFinalResponse( final NHttpServerConnection conn, final State state) throws IOException, HttpException { final Outgoing outgoing = state.getOutgoing(); Asserts.notNull(outgoing, "Outgoing response"); final HttpRequest request = outgoing.getRequest(); final HttpResponse response = outgoing.getResponse(); final HttpContext context = outgoing.getContext(); context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); HttpEntity entity = response.getEntity(); if (entity != null && !canResponseHaveBody(request, response)) { response.setEntity(null); entity = null; } conn.submitResponse(response); if (entity == null) { completeResponse(outgoing, conn, state); } else { state.setResponseState(MessageState.BODY_STREAM); } } private void completeResponse( final Outgoing outgoing, final NHttpServerConnection conn, final State state) throws IOException, HttpException { final HttpContext context = outgoing.getContext(); final HttpResponse response = outgoing.getResponse(); final HttpAsyncResponseProducer responseProducer = outgoing.getProducer(); try { responseProducer.responseCompleted(context); state.setOutgoing(null); state.setCancellable(null); state.setResponseState(MessageState.READY); } finally { responseProducer.close(); } if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { conn.requestInput(); } } @SuppressWarnings("unchecked") private HttpAsyncRequestHandler getRequestHandler(final HttpRequest request) { HttpAsyncRequestHandler handler = null; if (this.handlerMapper != null) { handler = (HttpAsyncRequestHandler) this.handlerMapper.lookup(request); } if (handler == null) { handler = new NullRequestHandler(); } return handler; } static class Incoming { private final HttpRequest request; private final HttpAsyncRequestHandler handler; private final HttpAsyncRequestConsumer consumer; private final HttpContext context; Incoming( final HttpRequest request, final HttpAsyncRequestHandler handler, final HttpAsyncRequestConsumer consumer, final HttpContext context) { this.request = request; this.handler = handler; this.consumer = consumer; this.context = context; } public HttpRequest getRequest() { return this.request; } public HttpAsyncRequestHandler getHandler() { return this.handler; } public HttpAsyncRequestConsumer getConsumer() { return this.consumer; } public HttpContext getContext() { return this.context; } } static class Outgoing { private final HttpRequest request; private final HttpResponse response; private final HttpAsyncResponseProducer producer; private final HttpContext context; Outgoing( final HttpRequest request, final HttpResponse response, final HttpAsyncResponseProducer producer, final HttpContext context) { this.request = request; this.response = response; this.producer = producer; this.context = context; } public HttpRequest getRequest() { return this.request; } public HttpResponse getResponse() { return this.response; } public HttpAsyncResponseProducer getProducer() { return this.producer; } public HttpContext getContext() { return this.context; } } static class PipelineEntry { private final HttpRequest request; private final Object result; private final Exception exception; private final HttpAsyncRequestHandler handler; private final HttpContext context; PipelineEntry( final HttpRequest request, final Object result, final Exception exception, final HttpAsyncRequestHandler handler, final HttpContext context) { this.request = request; this.result = result; this.exception = exception; this.handler = handler; this.context = context; } public HttpRequest getRequest() { return this.request; } public Object getResult() { return this.result; } public Exception getException() { return this.exception; } public HttpAsyncRequestHandler getHandler() { return this.handler; } public HttpContext getContext() { return this.context; } } static class State { private final Queue pipeline; private volatile boolean terminated; private volatile MessageState requestState; private volatile MessageState responseState; private volatile Incoming incoming; private volatile Outgoing outgoing; private volatile Cancellable cancellable; State() { super(); this.pipeline = new ConcurrentLinkedQueue(); this.requestState = MessageState.READY; this.responseState = MessageState.READY; } public boolean isTerminated() { return this.terminated; } public void setTerminated() { this.terminated = true; } public MessageState getRequestState() { return this.requestState; } public void setRequestState(final MessageState state) { this.requestState = state; } public MessageState getResponseState() { return this.responseState; } public void setResponseState(final MessageState state) { this.responseState = state; } public Incoming getIncoming() { return this.incoming; } public void setIncoming(final Incoming incoming) { this.incoming = incoming; } public Outgoing getOutgoing() { return this.outgoing; } public void setOutgoing(final Outgoing outgoing) { this.outgoing = outgoing; } public Cancellable getCancellable() { return this.cancellable; } public void setCancellable(final Cancellable cancellable) { this.cancellable = cancellable; } public Queue getPipeline() { return this.pipeline; } @Override public String toString() { final StringBuilder buf = new StringBuilder(); buf.append("[incoming "); buf.append(this.requestState); if (this.incoming != null) { buf.append(" "); buf.append(this.incoming.getRequest().getRequestLine()); } buf.append("; outgoing "); buf.append(this.responseState); if (this.outgoing != null) { buf.append(" "); buf.append(this.outgoing.getResponse().getStatusLine()); } buf.append("]"); return buf.toString(); } } class HttpAsyncExchangeImpl implements HttpAsyncExchange { private final AtomicBoolean completed = new AtomicBoolean(); private final HttpRequest request; private final HttpResponse response; private final State state; private final NHttpServerConnection conn; private final HttpContext context; public HttpAsyncExchangeImpl( final HttpRequest request, final HttpResponse response, final State state, final NHttpServerConnection conn, final HttpContext context) { super(); this.request = request; this.response = response; this.state = state; this.conn = conn; this.context = context; } @Override public HttpRequest getRequest() { return this.request; } @Override public HttpResponse getResponse() { return this.response; } @Override public void setCallback(final Cancellable cancellable) { if (this.completed.get()) { handleAlreadySubmittedResponse(cancellable, context); } else if (this.state.isTerminated() && cancellable != null) { cancellable.cancel(); } else { this.state.setCancellable(cancellable); } } @Override public void submitResponse(final HttpAsyncResponseProducer responseProducer) { Args.notNull(responseProducer, "Response producer"); if (this.completed.getAndSet(true)) { handleAlreadySubmittedResponse(responseProducer, context); } else if (!this.state.isTerminated()) { final HttpResponse response = responseProducer.generateResponse(); final Outgoing outgoing = new Outgoing( this.request, response, responseProducer, this.context); synchronized (this.state) { this.state.setOutgoing(outgoing); this.state.setCancellable(null); this.conn.requestOutput(); } } else { try { responseProducer.close(); } catch (final IOException ex) { log(ex); } } } @Override public void submitResponse() { submitResponse(new BasicAsyncResponseProducer(this.response)); } @Override public boolean isCompleted() { return this.completed.get(); } @Override public void setTimeout(final int timeout) { this.conn.setSocketTimeout(timeout); } @Override public int getTimeout() { return this.conn.getSocketTimeout(); } } /** * Adaptor class to transition from HttpAsyncRequestHandlerResolver to HttpAsyncRequestHandlerMapper. */ @Deprecated private static class HttpAsyncRequestHandlerResolverAdapter implements HttpAsyncRequestHandlerMapper { private final HttpAsyncRequestHandlerResolver resolver; public HttpAsyncRequestHandlerResolverAdapter(final HttpAsyncRequestHandlerResolver resolver) { this.resolver = resolver; } @Override public HttpAsyncRequestHandler lookup(final HttpRequest request) { return resolver.lookup(request.getRequestLine().getUri()); } } } ././@LongLink0100644 0000000 0000000 00000000164 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncExpectationVerifier.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncExpectati0100644 0000000 0000000 00000004021 12613456026 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.nio.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.protocol.HttpContext; /** * {@code HttpAsyncExpectationVerifier} defines a strategy to verify whether * or not an incoming HTTP request meets the target server's expectations. *

* 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.2 */ public interface HttpAsyncExpectationVerifier { void verify( HttpAsyncExchange httpExchange, HttpContext context) throws HttpException, IOException; } ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncRequestProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncRequestP0100644 0000000 0000000 00000013174 12613456026 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.nio.protocol; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.EntityAsyncContentProducer; import org.apache.http.nio.entity.HttpAsyncContentProducer; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Args; /** * Basic implementation of {@link HttpAsyncRequestProducer}. The producer * can make use of the {@link HttpAsyncContentProducer} interface to * efficiently stream out message content to the underlying non-blocking HTTP * connection, if it is implemented by the enclosed {@link HttpEntity}. * * @see HttpAsyncContentProducer * * @since 4.2 */ public class BasicAsyncRequestProducer implements HttpAsyncRequestProducer { private final HttpHost target; private final HttpRequest request; private final HttpAsyncContentProducer producer; /** * Creates a producer that can be used to transmit the given request * message. The given content producer will be used to stream out message * content. Please note that the request message is expected to enclose * an {@link HttpEntity} whose properties are consistent with the behavior * of the content producer. * * @param target target host. * @param request request message. * @param producer request content producer. */ protected BasicAsyncRequestProducer( final HttpHost target, final HttpEntityEnclosingRequest request, final HttpAsyncContentProducer producer) { super(); Args.notNull(target, "HTTP host"); Args.notNull(request, "HTTP request"); Args.notNull(producer, "HTTP content producer"); this.target = target; this.request = request; this.producer = producer; } /** * Creates a producer that can be used to transmit the given request * message. If the request message encloses an {@link HttpEntity} * it is also expected to implement {@link HttpAsyncContentProducer}. * * @param target target host. * @param request request message. */ public BasicAsyncRequestProducer(final HttpHost target, final HttpRequest request) { Args.notNull(target, "HTTP host"); Args.notNull(request, "HTTP request"); this.target = target; this.request = request; if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { if (entity instanceof HttpAsyncContentProducer) { this.producer = (HttpAsyncContentProducer) entity; } else { this.producer = new EntityAsyncContentProducer(entity); } } else { this.producer = null; } } else { this.producer = null; } } @Override public HttpRequest generateRequest() { return this.request; } @Override public HttpHost getTarget() { return this.target; } @Override public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { if (this.producer != null) { this.producer.produceContent(encoder, ioctrl); if (encoder.isCompleted()) { this.producer.close(); } } } @Override public void requestCompleted(final HttpContext context) { } @Override public void failed(final Exception ex) { } @Override public boolean isRepeatable() { return this.producer == null || this.producer.isRepeatable(); } @Override public void resetRequest() throws IOException { if (this.producer != null) { this.producer.close(); } } @Override public void close() throws IOException { if (this.producer != null) { this.producer.close(); } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(this.target); sb.append(' '); sb.append(this.request); if (this.producer != null) { sb.append(' '); sb.append(this.producer); } return sb.toString(); } } ././@LongLink0100644 0000000 0000000 00000000166 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncClientExchangeHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncClientExc0100644 0000000 0000000 00000014104 12613456026 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.nio.protocol; import java.io.Closeable; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.concurrent.Cancellable; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; /** * {@code HttpAsyncClientExchangeHandler} represents a callback interface whose * methods get invoked when executing one or multiple HTTP message exchanges * on the client side. *

* Individual {@code HttpAsyncClientExchangeHandler} are expected to make use of * a {@link org.apache.http.protocol.HttpProcessor} to generate mandatory protocol * headers for all outgoing messages and apply common, cross-cutting message * transformations to all incoming and outgoing messages. * {@code HttpAsyncClientExchangeHandler}s can delegate implementation * of application specific content generation and processing to * a {@link HttpAsyncRequestProducer} and a {@link HttpAsyncResponseConsumer}. * * @since 4.3 */ public interface HttpAsyncClientExchangeHandler extends Closeable, Cancellable { /** * Invoked to generate a HTTP request message head. The message is expected * to implement the {@link org.apache.http.HttpEntityEnclosingRequest} interface if it is * to enclose a content entity. The {@link #produceContent(ContentEncoder, * IOControl)} method will not be invoked if * {@link org.apache.http.HttpEntityEnclosingRequest#getEntity()} returns * {@code null}. * * @return HTTP request message. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ HttpRequest generateRequest() throws IOException, HttpException; /** * Invoked to write out a chunk of content to the {@link ContentEncoder}. * The {@link IOControl} interface can be used to suspend output event * notifications if the producer is temporarily unable to produce more content. *

* When all content is finished, the producer MUST call * {@link ContentEncoder#complete()}. Failure to do so may cause the entity * to be incorrectly delimited. *

* Please note that the {@link ContentEncoder} object is not thread-safe and * should only be used within the context of this method call. * The {@link IOControl} object can be shared and used on other thread * to resume output event notifications when more content is made available. * * @param encoder content encoder. * @param ioctrl I/O control of the underlying connection. * @throws IOException in case of an I/O error */ void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException; /** * Invoked to signal that the request has been fully written out. */ void requestCompleted(); /** * Invoked when a HTTP response message is received. Please note * that the {@link #consumeContent(ContentDecoder, IOControl)} method * will be invoked only if the response messages has a content entity * enclosed. * * @param response HTTP response message. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void responseReceived(HttpResponse response) throws IOException, HttpException; /** * Invoked to process a chunk of content from the {@link ContentDecoder}. * The {@link IOControl} interface can be used to suspend input event * notifications if the consumer is temporarily unable to process content. *

* The consumer can use the {@link ContentDecoder#isCompleted()} method * to find out whether or not the message content has been fully consumed. *

* Please note that the {@link ContentDecoder} object is not thread-safe and * should only be used within the context of this method call. * The {@link IOControl} object can be shared and used on other thread * to resume input event notifications when the consumer is capable of * processing more content. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. * @throws IOException in case of an I/O error */ void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Invoked to signal that the response has been fully processed. */ void responseCompleted() throws IOException, HttpException; /** * Invoked to signal that the connection has been terminated prematurely * by the opposite end. */ void inputTerminated(); /** * Invoked to signal that the response processing terminated abnormally. * * @param ex exception */ void failed(Exception ex); /** * Determines whether or not the response processing completed. */ boolean isDone(); } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncClientExchangeHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BasicAsyncClientEx0100644 0000000 0000000 00000021730 12613456026 032357 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.concurrent.BasicFuture; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; /** * Basic implementation of {@link HttpAsyncClientExchangeHandler} that executes * a single HTTP request / response exchange. * * @param the result type of request execution. * @since 4.3 */ public class BasicAsyncClientExchangeHandler implements HttpAsyncClientExchangeHandler { private final HttpAsyncRequestProducer requestProducer; private final HttpAsyncResponseConsumer responseConsumer; private final BasicFuture future; private final HttpContext localContext; private final NHttpClientConnection conn; private final HttpProcessor httppocessor; private final ConnectionReuseStrategy connReuseStrategy; private final AtomicBoolean requestSent; private final AtomicBoolean keepAlive; private final AtomicBoolean closed; /** * Creates new instance of BasicAsyncRequestExecutionHandler. * * @param requestProducer the request producer. * @param responseConsumer the response consumer. * @param callback the future callback invoked when the operation is completed. * @param localContext the local execution context. * @param conn the actual connection. * @param httppocessor the HTTP protocol processor. * @param connReuseStrategy the connection re-use strategy. */ public BasicAsyncClientExchangeHandler( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final FutureCallback callback, final HttpContext localContext, final NHttpClientConnection conn, final HttpProcessor httppocessor, final ConnectionReuseStrategy connReuseStrategy) { super(); this.requestProducer = Args.notNull(requestProducer, "Request producer"); this.responseConsumer = Args.notNull(responseConsumer, "Response consumer"); this.future = new BasicFuture(callback); this.localContext = Args.notNull(localContext, "HTTP context"); this.conn = Args.notNull(conn, "HTTP connection"); this.httppocessor = Args.notNull(httppocessor, "HTTP processor"); this.connReuseStrategy = connReuseStrategy != null ? connReuseStrategy : DefaultConnectionReuseStrategy.INSTANCE; this.requestSent = new AtomicBoolean(false); this.keepAlive = new AtomicBoolean(false); this.closed = new AtomicBoolean(false); } /** * Creates new instance of BasicAsyncRequestExecutionHandler. * * @param requestProducer the request producer. * @param responseConsumer the response consumer. * @param localContext the local execution context. * @param conn the actual connection. * @param httppocessor the HTTP protocol processor. */ public BasicAsyncClientExchangeHandler( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final HttpContext localContext, final NHttpClientConnection conn, final HttpProcessor httppocessor) { this(requestProducer, responseConsumer, null, localContext, conn, httppocessor, null); } public Future getFuture() { return this.future; } private void releaseResources() { try { this.responseConsumer.close(); } catch (final IOException ex) { } try { this.requestProducer.close(); } catch (final IOException ex) { } } @Override public void close() throws IOException { if (this.closed.compareAndSet(false, true)) { releaseResources(); if (!this.future.isDone()) { this.future.cancel(); } } } @Override public HttpRequest generateRequest() throws IOException, HttpException { if (isDone()) { return null; } final HttpRequest request = this.requestProducer.generateRequest(); this.localContext.setAttribute(HttpCoreContext.HTTP_REQUEST, request); this.localContext.setAttribute(HttpCoreContext.HTTP_CONNECTION, this.conn); this.httppocessor.process(request, this.localContext); return request; } @Override public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { this.requestProducer.produceContent(encoder, ioctrl); } @Override public void requestCompleted() { this.requestProducer.requestCompleted(this.localContext); this.requestSent.set(true); } @Override public void responseReceived(final HttpResponse response) throws IOException, HttpException { this.localContext.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); this.httppocessor.process(response, this.localContext); this.responseConsumer.responseReceived(response); this.keepAlive.set(this.connReuseStrategy.keepAlive(response, this.localContext)); } @Override public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { this.responseConsumer.consumeContent(decoder, ioctrl); } @Override public void responseCompleted() throws IOException { try { if (!this.keepAlive.get()) { this.conn.close(); } this.responseConsumer.responseCompleted(this.localContext); final T result = this.responseConsumer.getResult(); final Exception ex = this.responseConsumer.getException(); if (result != null) { this.future.completed(result); } else { this.future.failed(ex); } if (this.closed.compareAndSet(false, true)) { releaseResources(); } } catch (final RuntimeException ex) { failed(ex); throw ex; } } @Override public void inputTerminated() { failed(new ConnectionClosedException("Connection closed")); } @Override public void failed(final Exception ex) { if (this.closed.compareAndSet(false, true)) { try { if (!this.requestSent.get()) { this.requestProducer.failed(ex); } this.responseConsumer.failed(ex); } finally { try { this.future.failed(ex); } finally { releaseResources(); } } } } @Override public boolean cancel() { if (this.closed.compareAndSet(false, true)) { try { try { return this.responseConsumer.cancel(); } finally { this.future.cancel(); } } finally { releaseResources(); } } return false; } @Override public boolean isDone() { return this.responseConsumer.isDone(); } } ././@LongLink0100644 0000000 0000000 00000000165 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/AbstractAsyncResponseConsumer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/AbstractAsyncRespo0100644 0000000 0000000 00000014450 12613456026 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.nio.protocol; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.entity.ContentType; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HttpContext; /** * Abstract {@link HttpAsyncResponseConsumer} implementation that relieves its * subclasses from having to manage internal state and provides a number of protected * event methods that they need to implement. * * @since 4.2 */ public abstract class AbstractAsyncResponseConsumer implements HttpAsyncResponseConsumer { private final AtomicBoolean completed; private volatile T result; private volatile Exception ex; public AbstractAsyncResponseConsumer() { super(); this.completed = new AtomicBoolean(false); } /** * Invoked when a HTTP response message is received. Please note * that the {@link #onContentReceived(ContentDecoder, IOControl)} method * will be invoked only if the response messages has a content entity * enclosed. * * @param response HTTP response message. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ protected abstract void onResponseReceived( HttpResponse response) throws HttpException, IOException; /** * Invoked to process a chunk of content from the {@link ContentDecoder}. * The {@link IOControl} interface can be used to suspend input events * if the consumer is temporarily unable to consume more content. *

* The consumer can use the {@link ContentDecoder#isCompleted()} method * to find out whether or not the message content has been fully consumed. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. * @throws IOException in case of an I/O error */ protected abstract void onContentReceived( ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Invoked if the response message encloses a content entity. * * @param entity HTTP entity * @param contentType expected content type. * @throws IOException in case of an I/O error */ protected abstract void onEntityEnclosed( HttpEntity entity, ContentType contentType) throws IOException; /** * Invoked to generate a result object from the received HTTP response * message. * * @param context HTTP context. * @return result of the response processing. * @throws Exception in case of an abnormal termination. */ protected abstract T buildResult(HttpContext context) throws Exception; /** * Invoked to release all system resources currently allocated. */ protected abstract void releaseResources(); /** * Invoked when the consumer is being closed. * @throws IOException may be thrown by subclassses * * @since 4.3 */ protected void onClose() throws IOException { } /** * Use {@link #onResponseReceived(HttpResponse)} instead. */ @Override public final void responseReceived( final HttpResponse response) throws IOException, HttpException { onResponseReceived(response); final HttpEntity entity = response.getEntity(); if (entity != null) { final ContentType contentType = ContentType.getOrDefault(entity); onEntityEnclosed(entity, contentType); } } /** * Use {@link #onContentReceived(ContentDecoder, IOControl)} instead. */ @Override public final void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { onContentReceived(decoder, ioctrl); } /** * Use {@link #buildResult(HttpContext)} instead. */ @Override public final void responseCompleted(final HttpContext context) { if (this.completed.compareAndSet(false, true)) { try { this.result = buildResult(context); } catch (final Exception ex) { this.ex = ex; } finally { releaseResources(); } } } @Override public final boolean cancel() { if (this.completed.compareAndSet(false, true)) { releaseResources(); return true; } return false; } @Override public final void failed(final Exception ex) { if (this.completed.compareAndSet(false, true)) { this.ex = ex; releaseResources(); } } @Override public final void close() throws IOException { if (this.completed.compareAndSet(false, true)) { releaseResources(); onClose(); } } @Override public Exception getException() { return this.ex; } @Override public T getResult() { return this.result; } @Override public boolean isDone() { return this.completed.get(); } } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestHandlerResolver.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpAsyncRequestHa0100644 0000000 0000000 00000003542 12613456026 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.nio.protocol; /** * {@code HttpAsyncRequestHandlerResolver} can be used to map an instance * of {@link HttpAsyncRequestHandler} matching a particular request URI. * Usually the mapped request handler will be used to process the request * with the specified request URI. * * @since 4.2 * @deprecated see {@link HttpAsyncRequestHandlerMapper} */ @Deprecated public interface HttpAsyncRequestHandlerResolver { /** * Looks up a handler matching the given request URI. * * @param requestURI the request URI * @return HTTP request handler or {@code null} if no match * is found. */ HttpAsyncRequestHandler lookup(String requestURI); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/0040755 0000000 0000000 00000000000 12613456026 026071 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000145 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/RouteSpecificPool.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/RouteSpecificPool.java0100644 0000000 0000000 00000014460 12613456026 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.nio.pool; import java.net.ConnectException; 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 org.apache.http.annotation.NotThreadSafe; import org.apache.http.concurrent.BasicFuture; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.pool.PoolEntry; 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 Map> pending; RouteSpecificPool(final T route) { super(); this.route = route; this.leased = new HashSet(); this.available = new LinkedList(); this.pending = new HashMap>(); } public T getRoute() { return this.route; } protected abstract E createEntry(T route, C conn); 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() + this.pending.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 void addPending( final SessionRequest sessionRequest, final BasicFuture future) { this.pending.put(sessionRequest, future); } private BasicFuture removeRequest(final SessionRequest request) { final BasicFuture future = this.pending.remove(request); Asserts.notNull(future, "Session request future"); return future; } public E createEntry(final SessionRequest request, final C conn) { final E entry = createEntry(this.route, conn); this.leased.add(entry); return entry; } public void completed(final SessionRequest request, final E entry) { final BasicFuture future = removeRequest(request); future.completed(entry); } public void cancelled(final SessionRequest request) { final BasicFuture future = removeRequest(request); future.cancel(true); } public void failed(final SessionRequest request, final Exception ex) { final BasicFuture future = removeRequest(request); future.failed(ex); } public void timeout(final SessionRequest request) { final BasicFuture future = removeRequest(request); future.failed(new ConnectException()); } public void shutdown() { for (final SessionRequest sessionRequest: this.pending.keySet()) { sessionRequest.cancel(); } 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.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/package-info.java0100644 0000000 0000000 00000002441 12613456026 031256 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 asynchronous, event driven * communication. */ package org.apache.http.nio.pool; httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/LeaseRequest.java0100644 0000000 0000000 00000007147 12613456026 031344 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.pool; import org.apache.http.annotation.Immutable; import org.apache.http.concurrent.BasicFuture; import org.apache.http.pool.PoolEntry; import java.util.concurrent.atomic.AtomicBoolean; @Immutable class LeaseRequest> { private final T route; private final Object state; private final long connectTimeout; private final long deadline; private final BasicFuture future; private final AtomicBoolean completed; private volatile E result; private volatile Exception ex; /** * Contructor * @param route route * @param state state * @param connectTimeout http connection timeout * @param leaseTimeout timeout to wait in a request queue until kicked off * @param future future callback */ public LeaseRequest( final T route, final Object state, final long connectTimeout, final long leaseTimeout, final BasicFuture future) { super(); this.route = route; this.state = state; this.connectTimeout = connectTimeout; this.deadline = leaseTimeout > 0 ? System.currentTimeMillis() + leaseTimeout : Long.MAX_VALUE; this.future = future; this.completed = new AtomicBoolean(false); } public T getRoute() { return this.route; } public Object getState() { return this.state; } public long getConnectTimeout() { return this.connectTimeout; } public long getDeadline() { return this.deadline; } public boolean isDone() { return this.completed.get(); } public void failed(final Exception ex) { if (this.completed.compareAndSet(false, true)) { this.ex = ex; } } public void completed(final E result) { if (this.completed.compareAndSet(false, true)) { this.result = result; } } public BasicFuture getFuture() { return this.future; } public E getResult() { return this.result; } public Exception getException() { return this.ex; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append("["); buffer.append(this.route); buffer.append("]["); buffer.append(this.state); buffer.append("]"); return buffer.toString(); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/AbstractNIOConnPool.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/AbstractNIOConnPool.ja0100644 0000000 0000000 00000064602 12613456026 032173 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.pool; import java.io.IOException; import java.net.SocketAddress; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.http.annotation.ThreadSafe; import org.apache.http.concurrent.BasicFuture; import org.apache.http.concurrent.FutureCallback; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.pool.ConnPool; import org.apache.http.pool.ConnPoolControl; import org.apache.http.pool.PoolEntry; import org.apache.http.pool.PoolEntryCallback; import org.apache.http.pool.PoolStats; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * Abstract non-blocking connection pool. * * @param route * @param connection object * @param pool entry * * @since 4.2 */ @ThreadSafe public abstract class AbstractNIOConnPool> implements ConnPool, ConnPoolControl { private final ConnectingIOReactor ioreactor; private final NIOConnFactory connFactory; private final SocketAddressResolver addressResolver; private final SessionRequestCallback sessionRequestCallback; private final Map> routeToPool; private final LinkedList> leasingRequests; private final Set pending; private final Set leased; private final LinkedList available; private final ConcurrentLinkedQueue> completedRequests; private final Map maxPerRoute; private final Lock lock; private final AtomicBoolean isShutDown; private volatile int defaultMaxPerRoute; private volatile int maxTotal; /** * @deprecated use {@link AbstractNIOConnPool#AbstractNIOConnPool(ConnectingIOReactor, * NIOConnFactory, SocketAddressResolver, int, int)} */ @Deprecated public AbstractNIOConnPool( final ConnectingIOReactor ioreactor, final NIOConnFactory connFactory, final int defaultMaxPerRoute, final int maxTotal) { super(); Args.notNull(ioreactor, "I/O reactor"); Args.notNull(connFactory, "Connection factory"); Args.positive(defaultMaxPerRoute, "Max per route value"); Args.positive(maxTotal, "Max total value"); this.ioreactor = ioreactor; this.connFactory = connFactory; this.addressResolver = new SocketAddressResolver() { @Override public SocketAddress resolveLocalAddress(final T route) throws IOException { return AbstractNIOConnPool.this.resolveLocalAddress(route); } @Override public SocketAddress resolveRemoteAddress(final T route) throws IOException { return AbstractNIOConnPool.this.resolveRemoteAddress(route); } }; this.sessionRequestCallback = new InternalSessionRequestCallback(); this.routeToPool = new HashMap>(); this.leasingRequests = new LinkedList>(); this.pending = new HashSet(); this.leased = new HashSet(); this.available = new LinkedList(); this.maxPerRoute = new HashMap(); this.completedRequests = new ConcurrentLinkedQueue>(); this.lock = new ReentrantLock(); this.isShutDown = new AtomicBoolean(false); this.defaultMaxPerRoute = defaultMaxPerRoute; this.maxTotal = maxTotal; } /** * @since 4.3 */ public AbstractNIOConnPool( final ConnectingIOReactor ioreactor, final NIOConnFactory connFactory, final SocketAddressResolver addressResolver, final int defaultMaxPerRoute, final int maxTotal) { super(); Args.notNull(ioreactor, "I/O reactor"); Args.notNull(connFactory, "Connection factory"); Args.notNull(addressResolver, "Address resolver"); Args.positive(defaultMaxPerRoute, "Max per route value"); Args.positive(maxTotal, "Max total value"); this.ioreactor = ioreactor; this.connFactory = connFactory; this.addressResolver = addressResolver; this.sessionRequestCallback = new InternalSessionRequestCallback(); this.routeToPool = new HashMap>(); this.leasingRequests = new LinkedList>(); this.pending = new HashSet(); this.leased = new HashSet(); this.available = new LinkedList(); this.completedRequests = new ConcurrentLinkedQueue>(); this.maxPerRoute = new HashMap(); this.lock = new ReentrantLock(); this.isShutDown = new AtomicBoolean(false); this.defaultMaxPerRoute = defaultMaxPerRoute; this.maxTotal = maxTotal; } /** * @deprecated (4.3) use {@link SocketAddressResolver} */ @Deprecated protected SocketAddress resolveRemoteAddress(final T route) { return null; } /** * @deprecated (4.3) use {@link SocketAddressResolver} */ @Deprecated protected SocketAddress resolveLocalAddress(final T route) { return null; } protected abstract E createEntry(T route, C conn); /** * @since 4.3 */ protected void onLease(final E entry) { } /** * @since 4.3 */ protected void onRelease(final E entry) { } /** * @since 4.4 */ protected void onReuse(final E entry) { } public boolean isShutdown() { return this.isShutDown.get(); } public void shutdown(final long waitMs) throws IOException { if (this.isShutDown.compareAndSet(false, true)) { fireCallbacks(); this.lock.lock(); try { for (final SessionRequest sessionRequest: this.pending) { sessionRequest.cancel(); } 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.pending.clear(); this.available.clear(); this.leasingRequests.clear(); this.ioreactor.shutdown(waitMs); } 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 T route, final C conn) { return AbstractNIOConnPool.this.createEntry(route, conn); } }; this.routeToPool.put(route, pool); } return pool; } public Future lease( final T route, final Object state, final long connectTimeout, final TimeUnit tunit, final FutureCallback callback) { return this.lease(route, state, connectTimeout, connectTimeout, tunit, callback); } /** * @since 4.3 */ public Future lease( final T route, final Object state, final long connectTimeout, final long leaseTimeout, final TimeUnit tunit, final FutureCallback callback) { Args.notNull(route, "Route"); Args.notNull(tunit, "Time unit"); Asserts.check(!this.isShutDown.get(), "Connection pool shut down"); final BasicFuture future = new BasicFuture(callback); this.lock.lock(); try { final long timeout = connectTimeout > 0 ? tunit.toMillis(connectTimeout) : 0; final LeaseRequest request = new LeaseRequest(route, state, timeout, leaseTimeout, future); final boolean completed = processPendingRequest(request); if (!request.isDone() && !completed) { this.leasingRequests.add(request); } if (request.isDone()) { this.completedRequests.add(request); } } finally { this.lock.unlock(); } fireCallbacks(); return future; } @Override public Future lease(final T route, final Object state, final FutureCallback callback) { return lease(route, state, -1, TimeUnit.MICROSECONDS, callback); } public Future lease(final T route, final Object state) { return lease(route, state, -1, TimeUnit.MICROSECONDS, null); } @Override public void release(final E entry, final boolean reusable) { if (entry == null) { return; } if (this.isShutDown.get()) { return; } this.lock.lock(); try { if (this.leased.remove(entry)) { final RouteSpecificPool pool = getPool(entry.getRoute()); pool.free(entry, reusable); if (reusable) { this.available.addFirst(entry); onRelease(entry); } else { entry.close(); } processNextPendingRequest(); } } finally { this.lock.unlock(); } fireCallbacks(); } private void processPendingRequests() { final ListIterator> it = this.leasingRequests.listIterator(); while (it.hasNext()) { final LeaseRequest request = it.next(); final boolean completed = processPendingRequest(request); if (request.isDone() || completed) { it.remove(); } if (request.isDone()) { this.completedRequests.add(request); } } } private void processNextPendingRequest() { final ListIterator> it = this.leasingRequests.listIterator(); while (it.hasNext()) { final LeaseRequest request = it.next(); final boolean completed = processPendingRequest(request); if (request.isDone() || completed) { it.remove(); } if (request.isDone()) { this.completedRequests.add(request); } if (completed) { return; } } } private boolean processPendingRequest(final LeaseRequest request) { final T route = request.getRoute(); final Object state = request.getState(); final long deadline = request.getDeadline(); final long now = System.currentTimeMillis(); if (now > deadline) { request.failed(new TimeoutException()); return false; } final RouteSpecificPool pool = getPool(route); E entry; 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); request.completed(entry); onReuse(entry); onLease(entry); return true; } // 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.pending.size() + this.leased.size(); final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0); if (freeCapacity == 0) { return false; } 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 SocketAddress localAddress; final SocketAddress remoteAddress; try { remoteAddress = this.addressResolver.resolveRemoteAddress(route); localAddress = this.addressResolver.resolveLocalAddress(route); } catch (final IOException ex) { request.failed(ex); return false; } final SessionRequest sessionRequest = this.ioreactor.connect( remoteAddress, localAddress, route, this.sessionRequestCallback); final int timout = request.getConnectTimeout() < Integer.MAX_VALUE ? (int) request.getConnectTimeout() : Integer.MAX_VALUE; sessionRequest.setConnectTimeout(timout); this.pending.add(sessionRequest); pool.addPending(sessionRequest, request.getFuture()); return true; } else { return false; } } private void fireCallbacks() { LeaseRequest request; while ((request = this.completedRequests.poll()) != null) { final BasicFuture future = request.getFuture(); final Exception ex = request.getException(); final E result = request.getResult(); if (ex != null) { future.failed(ex); } else if (result != null) { future.completed(result); } else { future.cancel(); } } } public void validatePendingRequests() { this.lock.lock(); try { final long now = System.currentTimeMillis(); final ListIterator> it = this.leasingRequests.listIterator(); while (it.hasNext()) { final LeaseRequest request = it.next(); final long deadline = request.getDeadline(); if (now > deadline) { it.remove(); request.failed(new TimeoutException()); this.completedRequests.add(request); } } } finally { this.lock.unlock(); } fireCallbacks(); } protected void requestCompleted(final SessionRequest request) { if (this.isShutDown.get()) { return; } @SuppressWarnings("unchecked") final T route = (T) request.getAttachment(); this.lock.lock(); try { this.pending.remove(request); final RouteSpecificPool pool = getPool(route); final IOSession session = request.getSession(); try { final C conn = this.connFactory.create(route, session); final E entry = pool.createEntry(request, conn); this.leased.add(entry); pool.completed(request, entry); onLease(entry); } catch (final IOException ex) { pool.failed(request, ex); } } finally { this.lock.unlock(); } fireCallbacks(); } protected void requestCancelled(final SessionRequest request) { if (this.isShutDown.get()) { return; } @SuppressWarnings("unchecked") final T route = (T) request.getAttachment(); this.lock.lock(); try { this.pending.remove(request); final RouteSpecificPool pool = getPool(route); pool.cancelled(request); if (this.ioreactor.getStatus().compareTo(IOReactorStatus.ACTIVE) <= 0) { processNextPendingRequest(); } } finally { this.lock.unlock(); } fireCallbacks(); } protected void requestFailed(final SessionRequest request) { if (this.isShutDown.get()) { return; } @SuppressWarnings("unchecked") final T route = (T) request.getAttachment(); this.lock.lock(); try { this.pending.remove(request); final RouteSpecificPool pool = getPool(route); pool.failed(request, request.getException()); processNextPendingRequest(); } finally { this.lock.unlock(); } fireCallbacks(); } protected void requestTimeout(final SessionRequest request) { if (this.isShutDown.get()) { return; } @SuppressWarnings("unchecked") final T route = (T) request.getAttachment(); this.lock.lock(); try { this.pending.remove(request); final RouteSpecificPool pool = getPool(route); pool.timeout(request); processNextPendingRequest(); } finally { this.lock.unlock(); } fireCallbacks(); } private int getMax(final T route) { final Integer v = this.maxPerRoute.get(route); if (v != null) { return v.intValue(); } else { return this.defaultMaxPerRoute; } } @Override public void setMaxTotal(final int max) { Args.positive(max, "Max value"); this.lock.lock(); try { this.maxTotal = max; } finally { this.lock.unlock(); } } @Override public int getMaxTotal() { this.lock.lock(); try { return this.maxTotal; } finally { this.lock.unlock(); } } @Override public void setDefaultMaxPerRoute(final int max) { Args.positive(max, "Max value"); this.lock.lock(); try { this.defaultMaxPerRoute = max; } finally { this.lock.unlock(); } } @Override public int getDefaultMaxPerRoute() { this.lock.lock(); try { return this.defaultMaxPerRoute; } finally { this.lock.unlock(); } } @Override public void setMaxPerRoute(final T route, final int max) { Args.notNull(route, "Route"); Args.positive(max, "Max value"); this.lock.lock(); try { this.maxPerRoute.put(route, Integer.valueOf(max)); } finally { this.lock.unlock(); } } @Override public int getMaxPerRoute(final T route) { Args.notNull(route, "Route"); this.lock.lock(); try { return getMax(route); } finally { this.lock.unlock(); } } @Override public PoolStats getTotalStats() { this.lock.lock(); try { return new PoolStats( this.leased.size(), this.pending.size(), this.available.size(), this.maxTotal); } finally { this.lock.unlock(); } } @Override public PoolStats getStats(final T route) { Args.notNull(route, "Route"); this.lock.lock(); try { final RouteSpecificPool pool = getPool(route); return new PoolStats( pool.getLeasedCount(), pool.getPendingCount(), pool.getAvailableCount(), getMax(route)); } finally { this.lock.unlock(); } } /** * Returns snapshot of all knows routes * * @since 4.4 */ public Set getRoutes() { this.lock.lock(); try { return new HashSet(routeToPool.keySet()); } finally { this.lock.unlock(); } } /** * Enumerates all available connections. * * @since 4.3 */ protected void enumAvailable(final PoolEntryCallback callback) { this.lock.lock(); try { final Iterator it = this.available.iterator(); while (it.hasNext()) { final E entry = it.next(); callback.process(entry); if (entry.isClosed()) { final RouteSpecificPool pool = getPool(entry.getRoute()); pool.remove(entry); it.remove(); } } processPendingRequests(); 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); } processPendingRequests(); } finally { this.lock.unlock(); } } /** * Use {@link #enumLeased(org.apache.http.pool.PoolEntryCallback)} * or {@link #enumAvailable(org.apache.http.pool.PoolEntryCallback)} instead. * * @deprecated (4.3.2) */ @Deprecated protected void enumEntries(final Iterator it, final PoolEntryCallback callback) { while (it.hasNext()) { final E entry = it.next(); callback.process(entry); } processPendingRequests(); } 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.getAllocatedCount() == 0) { it.remove(); } } } public void closeIdle(final long idletime, final TimeUnit tunit) { Args.notNull(tunit, "Time unit"); long time = tunit.toMillis(idletime); if (time < 0) { time = 0; } final long deadline = System.currentTimeMillis() - time; enumAvailable(new PoolEntryCallback() { @Override public void process(final PoolEntry entry) { if (entry.getUpdated() <= deadline) { entry.close(); } } }); } public void closeExpired() { final long now = System.currentTimeMillis(); enumAvailable(new PoolEntryCallback() { @Override 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(); } class InternalSessionRequestCallback implements SessionRequestCallback { @Override public void completed(final SessionRequest request) { requestCompleted(request); } @Override public void cancelled(final SessionRequest request) { requestCancelled(request); } @Override public void failed(final SessionRequest request) { requestFailed(request); } @Override public void timeout(final SessionRequest request) { requestTimeout(request); } } } ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/SocketAddressResolver.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/SocketAddressResolver.0100644 0000000 0000000 00000003070 12613456026 032347 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.pool; import java.io.IOException; import java.net.SocketAddress; /** * Strategy that resolves an abstract connection route to a local or a remote {@link SocketAddress}. * . * @since 4.3 */ public interface SocketAddressResolver { SocketAddress resolveLocalAddress(T route) throws IOException; SocketAddress resolveRemoteAddress(T route) throws IOException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/NIOConnFactory.java0100644 0000000 0000000 00000003107 12613456026 031525 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.pool; import java.io.IOException; import org.apache.http.nio.reactor.IOSession; /** * Factory for poolable non-blocking connections. * * @param the route type that represents the opposite endpoint of a pooled * connection. * @param the connection type. * @since 4.2 */ public interface NIOConnFactory { C create(T route, IOSession session) throws IOException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/0040755 0000000 0000000 00000000000 12613456027 026076 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/ContentOutputBuffer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/ContentOutputBuffer.ja0100644 0000000 0000000 00000005777 12613456027 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.nio.util; import java.io.IOException; import org.apache.http.nio.ContentEncoder; /** * Generic content output buffer. * * @since 4.0 */ public interface ContentOutputBuffer { /** * Writes content from this buffer to the given {@link ContentEncoder}. * * @param encoder content encoder. * @return number of bytes written. * @throws IOException in case of an I/O error. * * @deprecated (4.3) use implementation specific methods. */ @Deprecated int produceContent(ContentEncoder encoder) throws IOException; /** * Resets the buffer by clearing its state and stored content. */ void reset(); /** * @deprecated (4.2) No longer used. */ @Deprecated void flush() throws IOException; /** * Writes {@code len} bytes from the specified byte array * starting at offset {@code off} to this buffer. *

* If {@code off} is negative, or {@code len} is negative, or * {@code off+len} is greater than the length of the array * {@code b}, this method can throw a runtime exception. The exact type * of runtime exception thrown by this method depends on implementation. * * @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 the specified byte to this buffer. * * @param b the {@code byte}. * @exception IOException if an I/O error occurs. */ void write(int b) throws IOException; /** * Indicates the content has been fully written. * @exception IOException if an I/O error occurs. */ void writeCompleted() throws IOException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/ExpandableBuffer.java0100644 0000000 0000000 00000013042 12613456027 032133 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; import java.nio.ByteBuffer; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.BufferInfo; import org.apache.http.util.Args; /** * A buffer that expand its capacity on demand using {@link ByteBufferAllocator} * interface. Internally, this class is backed by an instance of * {@link ByteBuffer}. *

* This class is not thread safe. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public class ExpandableBuffer implements BufferInfo, org.apache.http.nio.util.BufferInfo { public final static int INPUT_MODE = 0; public final static int OUTPUT_MODE = 1; private final ByteBufferAllocator allocator; private int mode; protected ByteBuffer buffer = null; /** * Allocates buffer of the given size using the given allocator. * * @param buffersize the buffer size. * @param allocator allocator to be used to allocate {@link ByteBuffer}s. */ public ExpandableBuffer(final int buffersize, final ByteBufferAllocator allocator) { super(); Args.notNull(allocator, "ByteBuffer allocator"); this.allocator = allocator; this.buffer = allocator.allocate(buffersize); this.mode = INPUT_MODE; } /** * Returns the current mode: *

* {@link #INPUT_MODE}: the buffer is in the input mode. *

* {@link #OUTPUT_MODE}: the buffer is in the output mode. * * @return current input/output mode. */ protected int getMode() { return this.mode; } /** * Sets output mode. The buffer can now be read from. */ protected void setOutputMode() { if (this.mode != OUTPUT_MODE) { this.buffer.flip(); this.mode = OUTPUT_MODE; } } /** * Sets input mode. The buffer can now be written into. */ protected void setInputMode() { if (this.mode != INPUT_MODE) { if (this.buffer.hasRemaining()) { this.buffer.compact(); } else { this.buffer.clear(); } this.mode = INPUT_MODE; } } private void expandCapacity(final int capacity) { final ByteBuffer oldbuffer = this.buffer; this.buffer = allocator.allocate(capacity); oldbuffer.flip(); this.buffer.put(oldbuffer); } /** * Expands buffer's capacity. */ protected void expand() { int newcapacity = (this.buffer.capacity() + 1) << 1; if (newcapacity < 0) { newcapacity = Integer.MAX_VALUE; } expandCapacity(newcapacity); } /** * Ensures the buffer can accommodate the required capacity. */ protected void ensureCapacity(final int requiredCapacity) { if (requiredCapacity > this.buffer.capacity()) { expandCapacity(requiredCapacity); } } /** * Returns the total capacity of this buffer. * * @return total capacity. */ @Override public int capacity() { return this.buffer.capacity(); } /** * Determines if the buffer contains data. * * @return {@code true} if there is data in the buffer, * {@code false} otherwise. */ public boolean hasData() { setOutputMode(); return this.buffer.hasRemaining(); } /** * Returns the length of this buffer. * * @return buffer length. */ @Override public int length() { setOutputMode(); return this.buffer.remaining(); } /** * Returns available capacity of this buffer. * * @return buffer length. */ @Override public int available() { setInputMode(); return this.buffer.remaining(); } /** * Clears buffer. */ protected void clear() { this.buffer.clear(); this.mode = INPUT_MODE; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("[mode="); if (getMode() == INPUT_MODE) { sb.append("in"); } else { sb.append("out"); } sb.append(" pos="); sb.append(this.buffer.position()); sb.append(" lim="); sb.append(this.buffer.limit()); sb.append(" cap="); sb.append(this.buffer.capacity()); sb.append("]"); return sb.toString(); } } ././@LongLink0100644 0000000 0000000 00000000146 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/ContentInputBuffer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/ContentInputBuffer.jav0100644 0000000 0000000 00000006524 12613456027 032370 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; import java.io.IOException; import org.apache.http.nio.ContentDecoder; /** * Generic content input buffer. * * @since 4.0 */ public interface ContentInputBuffer { /** * Reads content from the given {@link ContentDecoder} and stores it in * this buffer. * * @param decoder the content decoder. * @return number of bytes read. * @throws IOException in case of an I/O error. * * @deprecated (4.3) use implementation specific methods. */ @Deprecated int consumeContent(ContentDecoder decoder) throws IOException; /** * Resets the buffer by clearing its state and stored content. */ void reset(); /** * Reads up to {@code len} bytes of data from this buffer into * an array of bytes. The exact number of bytes read depends how many bytes * are stored in the buffer. * *

If {@code off} is negative, or {@code len} is negative, or * {@code off+len} is greater than the length of the array * {@code b}, this method can throw a runtime exception. The exact type * of runtime exception thrown by this method depends on implementation. * This method returns {@code -1} if the end of content stream has been * reached. * * @param b the buffer into which the data is read. * @param off the start offset in array {@code b} * at which the data is written. * @param len the maximum number of bytes to read. * @return the total number of bytes read into the buffer, or * {@code -1} if there is no more data because the end of * the stream has been reached. * @exception IOException if an I/O error occurs. */ int read(byte[] b, int off, int len) throws IOException; /** * Reads one byte from this buffer. If the buffer is empty this method can * throw a runtime exception. The exact type of runtime exception thrown * by this method depends on implementation. This method returns * {@code -1} if the end of content stream has been reached. * * @return one byte */ int read() throws IOException; } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/ByteBufferAllocator.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/ByteBufferAllocator.ja0100644 0000000 0000000 00000003035 12613456027 032306 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; import java.nio.ByteBuffer; /** * Abstract interface to allocate {@link ByteBuffer} instances. * * @since 4.0 */ public interface ByteBufferAllocator { /** * Allocates {@link ByteBuffer} of the given size. * * @param size the size of the buffer. * @return byte buffer. */ ByteBuffer allocate(int size); } ././@LongLink0100644 0000000 0000000 00000000153 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/HeapByteBufferAllocator.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/HeapByteBufferAllocato0100644 0000000 0000000 00000003333 12613456027 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.nio.util; import java.nio.ByteBuffer; import org.apache.http.annotation.Immutable; /** * Allocates {@link ByteBuffer} instances using * {@link ByteBuffer#allocate(int)}. * * @since 4.0 */ @Immutable public class HeapByteBufferAllocator implements ByteBufferAllocator { public static final HeapByteBufferAllocator INSTANCE = new HeapByteBufferAllocator(); public HeapByteBufferAllocator() { super(); } @Override public ByteBuffer allocate(final int size) { return ByteBuffer.allocate(size); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/BufferInfo.java0100644 0000000 0000000 00000002646 12613456027 030773 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; /** * Basic buffer properties. * * @since 4.0 * * @deprecated (4.1) Use {@link org.apache.http.io.BufferInfo} */ @Deprecated public interface BufferInfo { int length(); int capacity(); int available(); } ././@LongLink0100644 0000000 0000000 00000000145 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/SharedInputBuffer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/SharedInputBuffer.java0100644 0000000 0000000 00000020560 12613456027 032321 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; import java.io.IOException; import java.io.InterruptedIOException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; /** * Implementation of the {@link ContentInputBuffer} interface that can be * shared by multiple threads, usually the I/O dispatch of an I/O reactor and * a worker thread. *

* The I/O dispatch thread is expect to transfer data from {@link ContentDecoder} to the buffer * by calling {@link #consumeContent(ContentDecoder)}. *

* The worker thread is expected to read the data from the buffer by calling * {@link #read()} or {@link #read(byte[], int, int)} methods. *

* In case of an abnormal situation or when no longer needed the buffer must be shut down * using {@link #shutdown()} method. * * @since 4.0 */ @ThreadSafe public class SharedInputBuffer extends ExpandableBuffer implements ContentInputBuffer { private final ReentrantLock lock; private final Condition condition; private volatile IOControl ioctrl; private volatile boolean shutdown = false; private volatile boolean endOfStream = false; /** * @deprecated (4.3) use {@link SharedInputBuffer#SharedInputBuffer(int, ByteBufferAllocator)} */ @Deprecated public SharedInputBuffer(final int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) { super(buffersize, allocator); this.ioctrl = ioctrl; this.lock = new ReentrantLock(); this.condition = this.lock.newCondition(); } /** * @since 4.3 */ public SharedInputBuffer(final int buffersize, final ByteBufferAllocator allocator) { super(buffersize, allocator); this.lock = new ReentrantLock(); this.condition = this.lock.newCondition(); } /** * @since 4.3 */ public SharedInputBuffer(final int buffersize) { this(buffersize, HeapByteBufferAllocator.INSTANCE); } @Override public void reset() { if (this.shutdown) { return; } this.lock.lock(); try { clear(); this.endOfStream = false; } finally { this.lock.unlock(); } } /** * @deprecated (4.3) use {@link #consumeContent(ContentDecoder, IOControl)} */ @Override @Deprecated public int consumeContent(final ContentDecoder decoder) throws IOException { return consumeContent(decoder, null); } /** * @since 4.3 */ public int consumeContent(final ContentDecoder decoder, final IOControl ioctrl) throws IOException { if (this.shutdown) { return -1; } this.lock.lock(); try { if (ioctrl != null) { this.ioctrl = ioctrl; } setInputMode(); int totalRead = 0; int bytesRead; while ((bytesRead = decoder.read(this.buffer)) > 0) { totalRead += bytesRead; } if (bytesRead == -1 || decoder.isCompleted()) { this.endOfStream = true; } if (!this.buffer.hasRemaining()) { if (this.ioctrl != null) { this.ioctrl.suspendInput(); } } this.condition.signalAll(); if (totalRead > 0) { return totalRead; } else { if (this.endOfStream) { return -1; } else { return 0; } } } finally { this.lock.unlock(); } } @Override public boolean hasData() { this.lock.lock(); try { return super.hasData(); } finally { this.lock.unlock(); } } @Override public int available() { this.lock.lock(); try { return super.available(); } finally { this.lock.unlock(); } } @Override public int capacity() { this.lock.lock(); try { return super.capacity(); } finally { this.lock.unlock(); } } @Override public int length() { this.lock.lock(); try { return super.length(); } finally { this.lock.unlock(); } } protected void waitForData() throws IOException { this.lock.lock(); try { try { while (!super.hasData() && !this.endOfStream) { if (this.shutdown) { throw new InterruptedIOException("Input operation aborted"); } if (this.ioctrl != null) { this.ioctrl.requestInput(); } this.condition.await(); } } catch (final InterruptedException ex) { throw new IOException("Interrupted while waiting for more data"); } } finally { this.lock.unlock(); } } public void close() { if (this.shutdown) { return; } this.endOfStream = true; this.lock.lock(); try { this.condition.signalAll(); } finally { this.lock.unlock(); } } public void shutdown() { if (this.shutdown) { return; } this.shutdown = true; this.lock.lock(); try { this.condition.signalAll(); } finally { this.lock.unlock(); } } protected boolean isShutdown() { return this.shutdown; } protected boolean isEndOfStream() { return this.shutdown || (!hasData() && this.endOfStream); } @Override public int read() throws IOException { if (this.shutdown) { return -1; } this.lock.lock(); try { if (!hasData()) { waitForData(); } if (isEndOfStream()) { return -1; } return this.buffer.get() & 0xff; } finally { this.lock.unlock(); } } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (this.shutdown) { return -1; } if (b == null) { return 0; } this.lock.lock(); try { if (!hasData()) { waitForData(); } if (isEndOfStream()) { return -1; } setOutputMode(); int chunk = len; if (chunk > this.buffer.remaining()) { chunk = this.buffer.remaining(); } this.buffer.get(b, off, chunk); return chunk; } finally { this.lock.unlock(); } } public int read(final byte[] b) throws IOException { if (this.shutdown) { return -1; } if (b == null) { return 0; } return read(b, 0, b.length); } } ././@LongLink0100644 0000000 0000000 00000000146 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/SimpleOutputBuffer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/SimpleOutputBuffer.jav0100644 0000000 0000000 00000006435 12613456027 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.nio.util; import java.io.IOException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.nio.ContentEncoder; /** * Basic implementation of the {@link ContentOutputBuffer} interface. *

* This class is not thread safe. * * @since 4.0 */ @NotThreadSafe public class SimpleOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer { private boolean endOfStream; public SimpleOutputBuffer(final int buffersize, final ByteBufferAllocator allocator) { super(buffersize, allocator); this.endOfStream = false; } /** * @since 4.3 */ public SimpleOutputBuffer(final int buffersize) { this(buffersize, HeapByteBufferAllocator.INSTANCE); } @Override public int produceContent(final ContentEncoder encoder) throws IOException { setOutputMode(); final int bytesWritten = encoder.write(this.buffer); if (!hasData() && this.endOfStream) { encoder.complete(); } return bytesWritten; } @Override public void write(final byte[] b, final int off, final int len) throws IOException { if (b == null) { return; } if (this.endOfStream) { return; } setInputMode(); ensureCapacity(this.buffer.position() + len); this.buffer.put(b, off, len); } public void write(final byte[] b) throws IOException { if (b == null) { return; } if (this.endOfStream) { return; } write(b, 0, b.length); } @Override public void write(final int b) throws IOException { if (this.endOfStream) { return; } setInputMode(); ensureCapacity(this.capacity() + 1); this.buffer.put((byte)b); } @Override public void reset() { super.clear(); this.endOfStream = false; } @Override public void flush() { } @Override public void writeCompleted() { this.endOfStream = true; } public void shutdown() { this.endOfStream = true; } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/package-info.java0100644 0000000 0000000 00000002421 12613456027 031261 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 for asynchronous, event driven communication. */ package org.apache.http.nio.util; ././@LongLink0100644 0000000 0000000 00000000145 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/SimpleInputBuffer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/SimpleInputBuffer.java0100644 0000000 0000000 00000007133 12613456027 032345 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; import java.io.IOException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.nio.ContentDecoder; /** * Basic implementation of the {@link ContentInputBuffer} interface. *

* This class is not thread safe. * * @since 4.0 */ @NotThreadSafe public class SimpleInputBuffer extends ExpandableBuffer implements ContentInputBuffer { private boolean endOfStream = false; public SimpleInputBuffer(final int buffersize, final ByteBufferAllocator allocator) { super(buffersize, allocator); } /** * @since 4.3 */ public SimpleInputBuffer(final int buffersize) { this(buffersize, HeapByteBufferAllocator.INSTANCE); } @Override public void reset() { this.endOfStream = false; super.clear(); } @Override public int consumeContent(final ContentDecoder decoder) throws IOException { setInputMode(); int totalRead = 0; int bytesRead; while ((bytesRead = decoder.read(this.buffer)) != -1) { if (bytesRead == 0) { if (!this.buffer.hasRemaining()) { expand(); } else { break; } } else { totalRead += bytesRead; } } if (bytesRead == -1 || decoder.isCompleted()) { this.endOfStream = true; } return totalRead; } public boolean isEndOfStream() { return !hasData() && this.endOfStream; } @Override public int read() throws IOException { if (isEndOfStream()) { return -1; } setOutputMode(); return this.buffer.get() & 0xff; } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (isEndOfStream()) { return -1; } if (b == null) { return 0; } setOutputMode(); int chunk = len; if (chunk > this.buffer.remaining()) { chunk = this.buffer.remaining(); } this.buffer.get(b, off, chunk); return chunk; } public int read(final byte[] b) throws IOException { if (isEndOfStream()) { return -1; } if (b == null) { return 0; } return read(b, 0, b.length); } public void shutdown() { this.endOfStream = true; } } ././@LongLink0100644 0000000 0000000 00000000146 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/SharedOutputBuffer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/SharedOutputBuffer.jav0100644 0000000 0000000 00000021324 12613456027 032360 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.util; import java.io.IOException; import java.io.InterruptedIOException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * Implementation of the {@link ContentOutputBuffer} interface that can be * shared by multiple threads, usually the I/O dispatch of an I/O reactor and * a worker thread. *

* The I/O dispatch thread is expected to transfer data from the buffer to * {@link ContentEncoder} by calling {@link #produceContent(ContentEncoder)}. *

* The worker thread is expected to write data to the buffer by calling * {@link #write(int)}, {@link #write(byte[], int, int)} or {@link #writeCompleted()} *

* In case of an abnormal situation or when no longer needed the buffer must be * shut down using {@link #shutdown()} method. * * @since 4.0 */ @ThreadSafe public class SharedOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer { private final ReentrantLock lock; private final Condition condition; private volatile IOControl ioctrl; private volatile boolean shutdown = false; private volatile boolean endOfStream = false; /** * @deprecated (4.3) use {@link SharedOutputBuffer#SharedOutputBuffer(int, ByteBufferAllocator)} */ @Deprecated public SharedOutputBuffer(final int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) { super(buffersize, allocator); Args.notNull(ioctrl, "I/O content control"); this.ioctrl = ioctrl; this.lock = new ReentrantLock(); this.condition = this.lock.newCondition(); } /** * @since 4.3 */ public SharedOutputBuffer(final int buffersize, final ByteBufferAllocator allocator) { super(buffersize, allocator); this.lock = new ReentrantLock(); this.condition = this.lock.newCondition(); } /** * @since 4.3 */ public SharedOutputBuffer(final int buffersize) { this(buffersize, HeapByteBufferAllocator.INSTANCE); } @Override public void reset() { if (this.shutdown) { return; } this.lock.lock(); try { clear(); this.endOfStream = false; } finally { this.lock.unlock(); } } @Override public boolean hasData() { this.lock.lock(); try { return super.hasData(); } finally { this.lock.unlock(); } } @Override public int available() { this.lock.lock(); try { return super.available(); } finally { this.lock.unlock(); } } @Override public int capacity() { this.lock.lock(); try { return super.capacity(); } finally { this.lock.unlock(); } } @Override public int length() { this.lock.lock(); try { return super.length(); } finally { this.lock.unlock(); } } /** * @deprecated (4.3) use {@link #produceContent(ContentEncoder, IOControl)} */ @Override @Deprecated public int produceContent(final ContentEncoder encoder) throws IOException { return produceContent(encoder, null); } /** * @since 4.3 */ public int produceContent(final ContentEncoder encoder, final IOControl ioctrl) throws IOException { if (this.shutdown) { return -1; } this.lock.lock(); try { if (ioctrl != null) { this.ioctrl = ioctrl; } setOutputMode(); int bytesWritten = 0; if (super.hasData()) { bytesWritten = encoder.write(this.buffer); if (encoder.isCompleted()) { this.endOfStream = true; } } if (!super.hasData()) { // No more buffered content // If at the end of the stream, terminate if (this.endOfStream && !encoder.isCompleted()) { encoder.complete(); } if (!this.endOfStream) { // suspend output events if (this.ioctrl != null) { this.ioctrl.suspendOutput(); } } } this.condition.signalAll(); return bytesWritten; } finally { this.lock.unlock(); } } public void close() { shutdown(); } public void shutdown() { if (this.shutdown) { return; } this.shutdown = true; this.lock.lock(); try { this.condition.signalAll(); } finally { this.lock.unlock(); } } @Override public void write(final byte[] b, final int off, final int len) throws IOException { if (b == null) { return; } int pos = off; this.lock.lock(); try { Asserts.check(!this.shutdown && !this.endOfStream, "Buffer already closed for writing"); setInputMode(); int remaining = len; while (remaining > 0) { if (!this.buffer.hasRemaining()) { flushContent(); setInputMode(); } final int chunk = Math.min(remaining, this.buffer.remaining()); this.buffer.put(b, pos, chunk); remaining -= chunk; pos += chunk; } } finally { this.lock.unlock(); } } public void write(final byte[] b) throws IOException { if (b == null) { return; } write(b, 0, b.length); } @Override public void write(final int b) throws IOException { this.lock.lock(); try { Asserts.check(!this.shutdown && !this.endOfStream, "Buffer already closed for writing"); setInputMode(); if (!this.buffer.hasRemaining()) { flushContent(); setInputMode(); } this.buffer.put((byte)b); } finally { this.lock.unlock(); } } @Override public void flush() throws IOException { } private void flushContent() throws IOException { this.lock.lock(); try { try { while (super.hasData()) { if (this.shutdown) { throw new InterruptedIOException("Output operation aborted"); } if (this.ioctrl != null) { this.ioctrl.requestOutput(); } this.condition.await(); } } catch (final InterruptedException ex) { throw new IOException("Interrupted while flushing the content buffer"); } } finally { this.lock.unlock(); } } @Override public void writeCompleted() throws IOException { this.lock.lock(); try { if (this.endOfStream) { return; } this.endOfStream = true; if (this.ioctrl != null) { this.ioctrl.requestOutput(); } } finally { this.lock.unlock(); } } } ././@LongLink0100644 0000000 0000000 00000000155 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/DirectByteBufferAllocator.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/util/DirectByteBufferAlloca0100644 0000000 0000000 00000003357 12613456027 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.nio.util; import java.nio.ByteBuffer; import org.apache.http.annotation.Immutable; /** * Allocates {@link ByteBuffer} instances using * {@link ByteBuffer#allocateDirect(int)}. * * @since 4.0 */ @Immutable public class DirectByteBufferAllocator implements ByteBufferAllocator { public static final DirectByteBufferAllocator INSTANCE = new DirectByteBufferAllocator(); public DirectByteBufferAllocator() { super(); } @Override public ByteBuffer allocate(final int size) { return ByteBuffer.allocateDirect(size); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/0040755 0000000 0000000 00000000000 12613456027 026435 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/EntityAsyncContentProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/EntityAsyncContentPr0100644 0000000 0000000 00000006447 12613456027 032477 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.apache.http.HttpEntity; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.util.Args; /** * Basic implementation of {@link HttpAsyncContentProducer} that relies on * inefficient and potentially blocking I/O operation redirection through * {@link Channels#newChannel(java.io.InputStream)}. * * @since 4.2 */ @NotThreadSafe public class EntityAsyncContentProducer implements HttpAsyncContentProducer { private final HttpEntity entity; private final ByteBuffer buffer; private ReadableByteChannel channel; public EntityAsyncContentProducer(final HttpEntity entity) { super(); Args.notNull(entity, "HTTP entity"); this.entity = entity; this.buffer = ByteBuffer.allocate(4096); } @Override public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { if (this.channel == null) { this.channel = Channels.newChannel(this.entity.getContent()); } final int i = this.channel.read(this.buffer); this.buffer.flip(); encoder.write(this.buffer); final boolean buffering = this.buffer.hasRemaining(); this.buffer.compact(); if (i == -1 && !buffering) { encoder.complete(); close(); } } @Override public boolean isRepeatable() { return this.entity.isRepeatable(); } @Override public void close() throws IOException { final ReadableByteChannel local = this.channel; this.channel = null; if (local != null) { local.close(); } if (this.entity.isStreaming()) { final InputStream instream = this.entity.getContent(); instream.close(); } } @Override public String toString() { return this.entity.toString(); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/NFileEntity.java0100644 0000000 0000000 00000015002 12613456027 031465 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.ContentEncoderChannel; import org.apache.http.nio.FileContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.util.Args; /** * A self contained, repeatable non-blocking entity that retrieves its content * 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. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public class NFileEntity extends AbstractHttpEntity implements HttpAsyncContentProducer, ProducingNHttpEntity { private final File file; private RandomAccessFile accessfile; private FileChannel fileChannel; private long idx = -1; private boolean useFileChannels; /** * Creates new instance of NFileEntity from the given source {@link File} * with the given content type. If {@code useFileChannels} is set to * {@code true}, the entity will try to use {@link FileContentEncoder} * interface to stream file content directly from the file channel. * * @param file the source file. * @param contentType the content type of the file. * @param useFileChannels flag whether the direct transfer from the file * channel should be attempted. * * @since 4.2 */ public NFileEntity(final File file, final ContentType contentType, final boolean useFileChannels) { Args.notNull(file, "File"); this.file = file; this.useFileChannels = useFileChannels; if (contentType != null) { setContentType(contentType.toString()); } } /** * @since 4.2 */ public NFileEntity(final File file) { Args.notNull(file, "File"); this.file = file; } /** * Creates new instance of NFileEntity from the given source {@link File} * with the given content type. * * @param file the source file. * @param contentType the content type of the file. * * @since 4.2 */ public NFileEntity(final File file, final ContentType contentType) { this(file, contentType, true); } /** * @deprecated (4.2) use {@link #NFileEntity(File, ContentType, boolean)} */ @Deprecated public NFileEntity(final File file, final String contentType, final boolean useFileChannels) { Args.notNull(file, "File"); this.file = file; this.useFileChannels = useFileChannels; setContentType(contentType); } /** * @deprecated (4.2) use {@link #NFileEntity(File, ContentType)} */ @Deprecated public NFileEntity(final File file, final String contentType) { this(file, contentType, true); } /** * {@inheritDoc} * * @since 4.2 */ @Override public void close() throws IOException { if (accessfile != null) { accessfile.close(); } accessfile = null; fileChannel = null; } /** * {@inheritDoc} * * @deprecated (4.2) use {@link #close()} */ @Deprecated public void finish() throws IOException { close(); } @Override public long getContentLength() { return file.length(); } @Override public boolean isRepeatable() { return true; } @Override public void produceContent(final ContentEncoder encoder, final IOControl ioctrl) throws IOException { if (accessfile == null) { accessfile = new RandomAccessFile(this.file, "r"); } if (fileChannel == null) { fileChannel = accessfile.getChannel(); idx = 0; } final long transferred; if (useFileChannels && encoder instanceof FileContentEncoder) { transferred = ((FileContentEncoder)encoder) .transfer(fileChannel, idx, Long.MAX_VALUE); } else { transferred = fileChannel. transferTo(idx, Long.MAX_VALUE, new ContentEncoderChannel(encoder)); } if (transferred > 0) { idx += transferred; } if (idx >= fileChannel.size()) { encoder.complete(); close(); } } @Override public boolean isStreaming() { return false; } @Override public InputStream getContent() throws IOException { return new FileInputStream(this.file); } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); final InputStream instream = new FileInputStream(this.file); try { final byte[] tmp = new byte[4096]; int l; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } outstream.flush(); } finally { instream.close(); } } } ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentOutputStream.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentOutputStream.0100644 0000000 0000000 00000004541 12613456027 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.nio.entity; import java.io.IOException; import java.io.OutputStream; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.nio.util.ContentOutputBuffer; import org.apache.http.util.Args; /** * {@link OutputStream} adaptor for {@link ContentOutputBuffer}. * * @since 4.0 */ @NotThreadSafe public class ContentOutputStream extends OutputStream { private final ContentOutputBuffer buffer; public ContentOutputStream(final ContentOutputBuffer buffer) { super(); Args.notNull(buffer, "Output buffer"); this.buffer = buffer; } @Override public void close() throws IOException { this.buffer.writeCompleted(); } @Override public void flush() throws IOException { } @Override public void write(final byte[] b, final int off, final int len) throws IOException { this.buffer.write(b, off, len); } @Override public void write(final byte[] b) throws IOException { if (b == null) { return; } this.buffer.write(b, 0, b.length); } @Override public void write(final int b) throws IOException { this.buffer.write(b); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/NStringEntity.java0100644 0000000 0000000 00000014151 12613456027 032060 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.protocol.HTTP; import org.apache.http.util.Args; /** * A simple, self contained, repeatable non-blocking entity that retrieves * its content from a {@link String} object. * * @since 4.0 * */ @SuppressWarnings("deprecation") @NotThreadSafe public class NStringEntity extends AbstractHttpEntity implements HttpAsyncContentProducer, ProducingNHttpEntity { private final byte[] b; private final ByteBuffer buf; /** * @deprecated (4.2) */ @Deprecated protected final byte[] content; /** * @deprecated (4.2) */ @Deprecated protected final ByteBuffer buffer; /** * Creates a NStringEntity with the specified content and content type. * * @param s content to be used. Not {@code null}. * @param contentType content type to be used. May be {@code null}, in which case * {@link ContentType#TEXT_PLAIN} is assumed. * * @throws IllegalArgumentException if the string parameter is null * * @since 4.2 */ public NStringEntity(final String s, final ContentType contentType) { Args.notNull(s, "Source string"); Charset charset = contentType != null ? contentType.getCharset() : null; if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } this.b = s.getBytes(charset); this.buf = ByteBuffer.wrap(this.b); this.content = b; this.buffer = this.buf; if (contentType != null) { setContentType(contentType.toString()); } } /** * Creates a NStringEntity with the specified content and charset. The MIME type defaults * to "text/plain". * * @param s 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 UnsupportedEncodingException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public NStringEntity(final String s, final String charset) throws UnsupportedEncodingException { this(s, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset)); } /** * Creates a NStringEntity with the specified content and charset. The MIME type defaults * to "text/plain". * * @param s 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 NStringEntity(final String s, final Charset charset) { this(s, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset)); } /** * Creates a NStringEntity with the specified content. The content type defaults to * {@link ContentType#TEXT_PLAIN}. * * @param s 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 NStringEntity(final String s) throws UnsupportedEncodingException { this(s, ContentType.DEFAULT_TEXT); } @Override public boolean isRepeatable() { return true; } @Override public long getContentLength() { return this.b.length; } /** * {@inheritDoc} * * @since 4.2 */ @Override public void close() { this.buf.rewind(); } /** * {@inheritDoc} * * @deprecated (4.2) use {@link #close()} */ @Deprecated public void finish() { close(); } @Override public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { encoder.write(this.buf); if (!this.buf.hasRemaining()) { encoder.complete(); } } @Override public boolean isStreaming() { return false; } @Override public InputStream getContent() { return new ByteArrayInputStream(this.b); } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); outstream.write(this.b); outstream.flush(); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/package-info.java0100644 0000000 0000000 00000002457 12613456027 031631 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 with support for * asynchronous, event driven communication. */ package org.apache.http.nio.entity; ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ConsumingNHttpEntity.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ConsumingNHttpEntity0100644 0000000 0000000 00000004511 12613456027 032473 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; /** * A non-blocking {@link HttpEntity} that allows content to be streamed from a * {@link ContentDecoder}. * * @since 4.0 * * @deprecated use (4.2) * {@link org.apache.http.nio.protocol.BasicAsyncRequestProducer} * or {@link org.apache.http.nio.protocol.BasicAsyncResponseProducer} */ @Deprecated public interface ConsumingNHttpEntity extends HttpEntity { /** * Notification that content is available to be read from the decoder. * {@link IOControl} instance passed as a parameter to the method can be * used to suspend input events if the entity is temporarily unable to * allocate more storage to accommodate all incoming content. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. */ void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Notification that any resources allocated for reading can be released. */ void finish() throws IOException; } ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ProducingNHttpEntity.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ProducingNHttpEntity0100644 0000000 0000000 00000004673 12613456027 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.nio.entity; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; /** * An {@link HttpEntity} that can stream content out into a * {@link ContentEncoder}. * * @since 4.0 * * @deprecated use (4.2) * {@link org.apache.http.nio.protocol.BasicAsyncRequestProducer} * or {@link org.apache.http.nio.protocol.BasicAsyncResponseProducer} */ @Deprecated public interface ProducingNHttpEntity extends HttpEntity { /** * Notification that content should be written to the encoder. * {@link IOControl} instance passed as a parameter to the method can be * used to suspend output events if the entity is temporarily unable to * produce more content. *

* When all content is finished, this MUST call {@link ContentEncoder#complete()}. * Failure to do so could result in the entity never being written. * * @param encoder content encoder. * @param ioctrl I/O control of the underlying connection. */ void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException; /** * Notification that any resources allocated for writing can be released. */ void finish() throws IOException; } ././@LongLink0100644 0000000 0000000 00000000156 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/HttpAsyncContentProducer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/HttpAsyncContentProd0100644 0000000 0000000 00000005413 12613456027 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.nio.entity; import java.io.Closeable; import java.io.IOException; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; /** * {@code HttpAsyncContentProducer} is a callback interface whose methods * get invoked to stream out message content to a non-blocking HTTP connection. * * @since 4.2 */ public interface HttpAsyncContentProducer extends Closeable { /** * Invoked to write out a chunk of content to the {@link ContentEncoder}. * The {@link IOControl} interface can be used to suspend output event * notifications if the entity is temporarily unable to produce more content. *

* When all content is finished, the producer MUST call * {@link ContentEncoder#complete()}. Failure to do so may cause the entity * to be incorrectly delimited. *

* Please note that the {@link ContentEncoder} object is not thread-safe and * should only be used within the context of this method call. * The {@link IOControl} object can be shared and used on other thread * to resume output event notifications when more content is made available. * * @param encoder content encoder. * @param ioctrl I/O control of the underlying connection. */ void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException; /** * 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. */ boolean isRepeatable(); } ././@LongLink0100644 0000000 0000000 00000000150 12613460517 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentInputStream.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentInputStream.j0100644 0000000 0000000 00000005307 12613456027 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.nio.entity; import java.io.IOException; import java.io.InputStream; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.io.BufferInfo; import org.apache.http.nio.util.ContentInputBuffer; import org.apache.http.util.Args; /** * {@link InputStream} adaptor for {@link ContentInputBuffer}. * * @since 4.0 */ @NotThreadSafe public class ContentInputStream extends InputStream { private final ContentInputBuffer buffer; public ContentInputStream(final ContentInputBuffer buffer) { super(); Args.notNull(buffer, "Input buffer"); this.buffer = buffer; } @Override public int available() throws IOException { if (this.buffer instanceof BufferInfo) { return ((BufferInfo) this.buffer).length(); } else { return super.available(); } } @Override public int read(final byte[] b, final int off, final int len) throws IOException { return this.buffer.read(b, off, len); } @Override public int read(final byte[] b) throws IOException { if (b == null) { return 0; } return this.buffer.read(b, 0, b.length); } @Override public int read() throws IOException { return this.buffer.read(); } @Override public void close() throws IOException { // read and discard the remainder of the message final byte tmp[] = new byte[1024]; while (this.buffer.read(tmp, 0, tmp.length) >= 0) { } super.close(); } } ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentBufferEntity.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentBufferEntity.0100644 0000000 0000000 00000004767 12613456027 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.nio.entity; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.nio.util.ContentInputBuffer; import org.apache.http.util.Args; /** * HTTP entity wrapper whose content is provided by a * {@link ContentInputBuffer}. * * @since 4.0 */ @NotThreadSafe public class ContentBufferEntity extends BasicHttpEntity { private final HttpEntity wrappedEntity; /** * Creates new instance of ContentBufferEntity. * * @param entity the original entity. * @param buffer the content buffer. */ public ContentBufferEntity(final HttpEntity entity, final ContentInputBuffer buffer) { super(); Args.notNull(entity, "HTTP entity"); this.wrappedEntity = entity; setContent(new ContentInputStream(buffer)); } @Override public boolean isChunked() { return this.wrappedEntity.isChunked(); } @Override public long getContentLength() { return this.wrappedEntity.getContentLength(); } @Override public Header getContentType() { return this.wrappedEntity.getContentType(); } @Override public Header getContentEncoding() { return this.wrappedEntity.getContentEncoding(); } } ././@LongLink0100644 0000000 0000000 00000000146 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/NByteArrayEntity.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/entity/NByteArrayEntity.jav0100644 0000000 0000000 00000011213 12613456027 032347 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.util.Args; /** * A simple self contained, repeatable non-blocking entity that retrieves * its content from a byte array. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public class NByteArrayEntity extends AbstractHttpEntity implements HttpAsyncContentProducer, ProducingNHttpEntity { private final byte[] b; private final int off, len; private final ByteBuffer buf; /** * @deprecated (4.2) */ @Deprecated protected final byte[] content; /** * @deprecated (4.2) */ @Deprecated protected final ByteBuffer buffer; /** * @since 4.2 */ public NByteArrayEntity(final byte[] b, final ContentType contentType) { super(); Args.notNull(b, "Source byte array"); this.b = b; this.off = 0; this.len = b.length; this.buf = ByteBuffer.wrap(b); this.content = b; this.buffer = this.buf; if (contentType != null) { setContentType(contentType.toString()); } } /** * @since 4.2 */ public NByteArrayEntity(final byte[] b, final int off, final int len, final ContentType contentType) { super(); Args.notNull(b, "Source byte array"); if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length); } this.b = b; this.off = off; this.len = len; this.buf = ByteBuffer.wrap(b, off, len); this.content = b; this.buffer = this.buf; if (contentType != null) { setContentType(contentType.toString()); } } public NByteArrayEntity(final byte[] b) { this(b, null); } public NByteArrayEntity(final byte[] b, final int off, final int len) { this(b, off, len, null); } /** * {@inheritDoc} * * @since 4.2 */ @Override public void close() { this.buf.rewind(); } /** * {@inheritDoc} * * @deprecated (4.2) use {@link #close()} */ @Deprecated public void finish() { close(); } @Override public void produceContent(final ContentEncoder encoder, final IOControl ioctrl) throws IOException { encoder.write(this.buf); if(!this.buf.hasRemaining()) { encoder.complete(); } } @Override public long getContentLength() { return this.len; } @Override public boolean isRepeatable() { return true; } @Override public boolean isStreaming() { return false; } @Override public InputStream getContent() { return new ByteArrayInputStream(this.b, this.off, this.len); } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); outstream.write(this.b, this.off, this.len); outstream.flush(); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/0040755 0000000 0000000 00000000000 12613456026 026557 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorException.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorException.0100644 0000000 0000000 00000003402 12613456026 032262 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.io.IOException; /** * I/O exception that can be thrown by an I/O reactor. Usually exceptions * of this type are fatal and are not recoverable. * * @since 4.0 */ public class IOReactorException extends IOException { private static final long serialVersionUID = -4248110651729635749L; public IOReactorException(final String message, final Exception cause) { super(message); if (cause != null) { initCause(cause); } } public IOReactorException(final String message) { super(message); } } ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionOutputBuffer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionOutputBuffer0100644 0000000 0000000 00000007670 12613456026 032507 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import org.apache.http.util.CharArrayBuffer; /** * Session output buffer for non-blocking connections. This interface * facilitates intermediate buffering of output data streamed out to * a destination channel and writing data to the buffer from a source, usually * {@link ByteBuffer} or {@link ReadableByteChannel}. This interface also * provides methods for writing lines of text. * * @since 4.0 */ public interface SessionOutputBuffer { /** * Determines if the buffer contains data. * * @return {@code true} if there is data in the buffer, * {@code false} otherwise. */ boolean hasData(); /** * Returns the length of this buffer. * * @return buffer length. */ int length(); /** * Makes an attempt to flush the content of this buffer to the given * destination {@link WritableByteChannel}. * * @param channel the destination channel. * @return The number of bytes written, possibly zero. * @throws IOException in case of an I/O error. */ int flush(WritableByteChannel channel) throws IOException; /** * Copies content of the source buffer into this buffer. The capacity of * the destination will be expanded in order to accommodate the entire * content of the source buffer. * * @param src the source buffer. */ void write(ByteBuffer src); /** * Reads a sequence of bytes from the source channel into this buffer. * * @param src the source channel. */ void write(ReadableByteChannel src) throws IOException; /** * Copies content of the source buffer into this buffer as one line of text * including a line delimiter. The capacity of the destination will be * expanded in order to accommodate the entire content of the source buffer. *

* The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param src the source buffer. */ void writeLine(CharArrayBuffer src) throws CharacterCodingException; /** * Copies content of the given string into this buffer as one line of text * including a line delimiter. * The capacity of the destination will be expanded in order to accommodate * the entire string. *

* The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param s the string. */ void writeLine(String s) throws IOException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/package-info.java0100644 0000000 0000000 00000003064 12613456026 031746 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ /** * Event driven network communication APIs loosely based on Doug Lea's reactor pattern.

This API is not specific to HTTP communication. However, it is minimal in the sense that it defines only what is required within the scope of HTTP protocol. */ package org.apache.http.nio.reactor; ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ConnectingIOReactor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ConnectingIOReactor0100644 0000000 0000000 00000006255 12613456026 032346 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.net.SocketAddress; /** * ConnectingIOReactor represents an I/O reactor capable of establishing * connections to remote hosts. * * @since 4.0 */ public interface ConnectingIOReactor extends IOReactor { /** * Requests a connection to a remote host. *

* 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 * {@link SessionRequest} interface. *

* There are several parameters one can use 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. *

* An attachment object can 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 * {@link SessionRequestCallback} instance to get notified of events related * to session requests, such as request completion, cancellation, failure or * timeout. * * @param remoteAddress the socket address of the remote host. * @param localAddress the local socket address. Can be {@code null}, * in which can the default local address and a random port will be used. * @param attachment the attachment object. Can be {@code null}. * @param callback interface. Can be {@code null}. * @return session request object. */ SessionRequest connect( SocketAddress remoteAddress, SocketAddress localAddress, Object attachment, SessionRequestCallback callback); } ././@LongLink0100644 0000000 0000000 00000000146 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOEventDispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOEventDispatch.jav0100644 0000000 0000000 00000005155 12613456026 032255 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; /** * IOEventDispatch interface is used by I/O reactors to notify clients of I/O * events pending for a particular session. All methods of this interface 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. * * @since 4.0 */ public interface IOEventDispatch { /** * Attribute name of an object that represents a non-blocking connection. */ public static final String CONNECTION_KEY = "http.connection"; /** * Triggered after the given session has been just created. * * @param session the I/O session. */ void connected(IOSession session); /** * Triggered when the given session has input pending. * * @param session the I/O session. */ void inputReady(IOSession session); /** * Triggered when the given session is ready for output. * * @param session the I/O session. */ void outputReady(IOSession session); /** * Triggered when the given session as timed out. * * @param session the I/O session. */ void timeout(IOSession session); /** * Triggered when the given session has been terminated. * * @param session the I/O session. */ void disconnected(IOSession session); } ././@LongLink0100644 0000000 0000000 00000000146 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorStatus.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorStatus.jav0100644 0000000 0000000 00000003321 12613456026 032310 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; /** * IOReactorStatus represents an internal status of an I/O reactor. * * @since 4.0 */ public enum IOReactorStatus { /** * The reactor is inactive / has not been started */ INACTIVE, /** * The reactor is active / processing I/O events. */ ACTIVE, /** * Shutdown of the reactor has been requested. */ SHUTDOWN_REQUEST, /** * The reactor is shutting down. */ SHUTTING_DOWN, /** * The reactor has shut down. */ SHUT_DOWN } ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorExceptionHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorExceptionH0100644 0000000 0000000 00000004606 12613456026 032323 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.io.IOException; /** * Abstract exception handler intended to deal with potentially recoverable * I/O exceptions thrown by an I/O reactor. * * @since 4.0 */ public interface IOReactorExceptionHandler { /** * This method is expected to examine the I/O exception passed as * a parameter and decide whether it is safe to continue execution of * the I/O reactor. * * @param ex potentially recoverable I/O exception * @return {@code true} if it is safe to ignore the exception * and continue execution of the I/O reactor; {@code false} if the * I/O reactor must throw {@link IOReactorException} and terminate */ boolean handle(IOException ex); /** * This method is expected to examine the runtime exception passed as * a parameter and decide whether it is safe to continue execution of * the I/O reactor. * * @param ex potentially recoverable runtime exception * @return {@code true} if it is safe to ignore the exception * and continue execution of the I/O reactor; {@code false} if the * I/O reactor must throw {@link RuntimeException} and terminate */ boolean handle(RuntimeException ex); } ././@LongLink0100644 0000000 0000000 00000000145 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SocketAccessor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SocketAccessor.java0100644 0000000 0000000 00000003027 12613456026 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.nio.reactor; import java.net.Socket; /** * Provides access to the underlying Socket. *

* Remark: this interface will be removed in the next major release. */ public interface SocketAccessor { /** * Return the underlying socket * * @return - the underlying Socket, may be {@code null}. */ Socket getSocket(); } ././@LongLink0100644 0000000 0000000 00000000155 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionRequestCallback.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionRequestCallb0100644 0000000 0000000 00000004531 12613456026 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.nio.reactor; /** * SessionRequestCallback interface can be used to get notifications of * completion of session requests asynchronously without having to wait * for it, blocking the current thread of execution. * * @since 4.0 */ public interface SessionRequestCallback { /** * Triggered on successful completion of a {@link SessionRequest}. * The {@link SessionRequest#getSession()} method can now be used to obtain * the new I/O session. * * @param request session request. */ void completed(SessionRequest request); /** * Triggered on unsuccessful completion a {@link SessionRequest}. * The {@link SessionRequest#getException()} method can now be used to * obtain the cause of the error. * * @param request session request. */ void failed(SessionRequest request); /** * Triggered if a {@link SessionRequest} times out. * * @param request session request. */ void timeout(SessionRequest request); /** * Triggered on cancellation of a {@link SessionRequest}. * * @param request session request. */ void cancelled(SessionRequest request); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOSession.java0100644 0000000 0000000 00000016530 12613456026 031277 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.net.SocketAddress; import java.nio.channels.ByteChannel; /** * IOSession interface represents a sequence of logically related data exchanges * between two end points. *

* The channel associated with implementations of this interface can be used to * read data from and write data to the session. *

* 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, usually * using execution context associated with it. *

* Implementations of this interface are expected to be threading safe. * * @since 4.0 */ public interface IOSession { /** * Name of the context attribute key, which can be used to obtain the * session attachment object. */ public static final String ATTACHMENT_KEY = "http.session.attachment"; public static final int ACTIVE = 0; public static final int CLOSING = 1; public static final int CLOSED = Integer.MAX_VALUE; /** * Returns the underlying I/O channel associated with this session. * * @return the I/O channel. */ ByteChannel channel(); /** * Returns address of the remote peer. * * @return socket address. */ SocketAddress getRemoteAddress(); /** * Returns local address. * * @return socket address. */ SocketAddress getLocalAddress(); /** * Returns mask of I/O evens this session declared interest in. * * @return I/O event mask. */ int getEventMask(); /** * Declares interest in I/O event notifications by setting the event mask * associated with the session * * @param ops new I/O event mask. */ void setEventMask(int ops); /** * Declares interest in a particular I/O event type by updating the event * mask associated with the session. * * @param op I/O event type. */ void setEvent(int op); /** * Clears interest in a particular I/O event type by updating the event * mask associated with the session. * * @param op I/O event type. */ void clearEvent(int op); /** * Terminates the session gracefully and closes the underlying I/O channel. * This method ensures that session termination handshake, such as the one * used by the SSL/TLS protocol, is correctly carried out. */ void close(); /** * Terminates the session by shutting down the underlying I/O channel. */ void shutdown(); /** * Returns status of the session: *

* {@link #ACTIVE}: session is active. *

* {@link #CLOSING}: session is being closed. *

* {@link #CLOSED}: session has been terminated. * * @return session status. */ int getStatus(); /** * Determines if the session has been terminated. * * @return {@code true} if the session has been terminated, * {@code false} otherwise. */ boolean isClosed(); /** * Returns value of the socket timeout in milliseconds. The value of * {@code 0} signifies the session cannot time out. * * @return socket timeout. */ int getSocketTimeout(); /** * Sets value of the socket timeout in milliseconds. The value of * {@code 0} signifies the session cannot time out. * * @param timeout socket timeout. */ void setSocketTimeout(int timeout); /** * 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 consumer can read * 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 {@link SessionBufferStatus} interface. */ void setBufferStatus(SessionBufferStatus status); /** * Determines if the input buffer associated with the session contains data. * * @return {@code true} if the session input buffer contains data, * {@code false} otherwise. */ boolean hasBufferedInput(); /** * Determines if the output buffer associated with the session contains * data. * * @return {@code true} if the session output buffer contains data, * {@code false} otherwise. */ boolean hasBufferedOutput(); /** * This method can be used to associate a particular object with the * session by the given attribute name. *

* 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. * * @param name name of the attribute. * @param obj value of the attribute. */ void setAttribute(String name, Object obj); /** * Returns the value of the attribute with the given name. The value can be * {@code null} if not set. *

* The value of the session attachment object can be obtained using * {@link #ATTACHMENT_KEY} name. * * @see #setAttribute(String, Object) * * @param name name of the attribute. * @return value of the attribute. */ Object getAttribute(String name); /** * Removes attribute with the given name. * * @see #setAttribute(String, Object) * * @param name name of the attribute to be removed. * @return value of the removed attribute. */ Object removeAttribute(String name); } ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionInputBuffer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionInputBuffer.0100644 0000000 0000000 00000015776 12613456026 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.nio.reactor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import org.apache.http.util.CharArrayBuffer; /** * Session input buffer for non-blocking connections. This interface facilitates * intermediate buffering of input data streamed from a source channel and * reading buffered data to a destination, usually {@link ByteBuffer} or * {@link WritableByteChannel}. This interface also provides methods for reading * lines of text. * * @since 4.0 */ public interface SessionInputBuffer { /** * Determines if the buffer contains data. * * @return {@code true} if there is data in the buffer, * {@code false} otherwise. */ boolean hasData(); /** * Returns the length of this buffer. * * @return buffer length. */ int length(); /** * Makes an attempt to fill the buffer with data from the given * {@link ReadableByteChannel}. * * @param src the source channel * @return The number of bytes read, possibly zero, or {@code -1} if the * channel has reached end-of-stream. * @throws IOException in case of an I/O error. */ int fill(ReadableByteChannel src) throws IOException; /** * Reads one byte from the buffer. If the buffer is empty this method can * throw a runtime exception. The exact type of runtime exception thrown * by this method depends on implementation. * * @return one byte */ int read(); /** * Reads a sequence of bytes from this buffer into the destination buffer, * up to the given maximum limit. The exact number of bytes transferred * depends on availability of data in this buffer and capacity of the * destination buffer, but cannot be more than {@code maxLen} value. * * @param dst the destination buffer. * @param maxLen the maximum number of bytes to be read. * @return The number of bytes read, possibly zero. */ int read(ByteBuffer dst, int maxLen); /** * Reads a sequence of bytes from this buffer into the destination buffer. * The exact number of bytes transferred depends on availability of data * in this buffer and capacity of the destination buffer. * * @param dst the destination buffer. * @return The number of bytes read, possibly zero. */ int read(ByteBuffer dst); /** * Reads a sequence of bytes from this buffer into the destination channel, * up to the given maximum limit. The exact number of bytes transferred * depends on availability of data in this buffer, but cannot be more than * {@code maxLen} value. * * @param dst the destination channel. * @param maxLen the maximum number of bytes to be read. * @return The number of bytes read, possibly zero. * @throws IOException in case of an I/O error. */ int read(WritableByteChannel dst, int maxLen) throws IOException; /** * Reads a sequence of bytes from this buffer into the destination channel. * The exact number of bytes transferred depends on availability of data in * this buffer. * * @param dst the destination channel. * @return The number of bytes read, possibly zero. * @throws IOException in case of an I/O error. */ int read(WritableByteChannel dst) throws IOException; /** * Attempts to transfer a complete line of characters up to a line delimiter * from this buffer to the destination buffer. If a complete line is * available in the buffer, the sequence of chars is transferred to the * destination buffer the method returns {@code true}. The line * delimiter itself is discarded. If a complete line is not available in * the buffer, this method returns {@code false} without transferring * anything to the destination buffer. If {@code endOfStream} parameter * is set to {@code true} this method assumes the end of stream has * been reached and the content currently stored in the buffer should be * treated as a complete line. *

* The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param dst the destination buffer. * @param endOfStream end of stream flag * @return {@code true} if a sequence of chars representing a complete * line has been transferred to the destination buffer, {@code false} * otherwise. * * @throws CharacterCodingException in case a character encoding or decoding * error occurs. */ boolean readLine(CharArrayBuffer dst, boolean endOfStream) throws CharacterCodingException; /** * Attempts to transfer a complete line of characters up to a line delimiter * from this buffer to a newly created string. If a complete line is * available in the buffer, the sequence of chars is transferred to a newly * created string. The line delimiter itself is discarded. If a complete * line is not available in the buffer, this method returns * {@code null}. If {@code endOfStream} parameter * is set to {@code true} this method assumes the end of stream has * been reached and the content currently stored in the buffer should be * treated as a complete line. *

* The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param endOfStream end of stream flag * @return a string representing a complete line, if available. * {@code null} otherwise. * * @throws CharacterCodingException in case a character encoding or decoding * error occurs. */ String readLine(boolean endOfStream) throws CharacterCodingException; } ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ListeningIOReactor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ListeningIOReactor.0100644 0000000 0000000 00000005403 12613456026 032263 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.io.IOException; import java.net.SocketAddress; import java.util.Set; /** * ListeningIOReactor represents an I/O reactor capable of listening for * incoming connections on one or several ports. * * @since 4.0 */ public interface ListeningIOReactor extends IOReactor { /** * Opens a new listener endpoint with the given socket address. Once * the endpoint is fully initialized it starts accepting incoming * connections and propagates I/O activity notifications to the I/O event * dispatcher. *

* {@link ListenerEndpoint#waitFor()} can be used to wait for the * listener to be come ready to accept incoming connections. *

* {@link ListenerEndpoint#close()} can be used to shut down * the listener even before it is fully initialized. * * @param address the socket address to listen on. * @return listener endpoint. */ ListenerEndpoint listen(SocketAddress address); /** * Suspends the I/O reactor preventing it from accepting new connections on * all active endpoints. * * @throws IOException in case of an I/O error. */ void pause() throws IOException; /** * Resumes the I/O reactor restoring its ability to accept incoming * connections on all active endpoints. * * @throws IOException in case of an I/O error. */ void resume() throws IOException; /** * Returns a set of endpoints for this I/O reactor. * * @return set of endpoints. */ Set getEndpoints(); } ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionBufferStatus.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionBufferStatus0100644 0000000 0000000 00000003444 12613456026 032465 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; /** * SessionBufferStatus interface is intended to query the status of session * I/O buffers. * * @since 4.0 */ public interface SessionBufferStatus { /** * Determines if the session input buffer contains data. * * @return {@code true} if the session input buffer contains data, * {@code false} otherwise. */ boolean hasBufferedInput(); /** * Determines if the session output buffer contains data. * * @return {@code true} if the session output buffer contains data, * {@code false} otherwise. */ boolean hasBufferedOutput(); } ././@LongLink0100644 0000000 0000000 00000000145 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionRequest.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionRequest.java0100644 0000000 0000000 00000007413 12613456026 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.nio.reactor; import java.io.IOException; import java.net.SocketAddress; /** * SessionRequest interface represents a request to establish a new connection * (or session) to a remote host. It can be used to monitor the status of the * request, to block waiting for its completion, or to cancel the request. *

* Implementations of this interface are expected to be threading safe. * * @since 4.0 */ public interface SessionRequest { /** * Returns socket address of the remote host. * * @return socket address of the remote host */ SocketAddress getRemoteAddress(); /** * Returns local socket address. * * @return local socket address. */ SocketAddress getLocalAddress(); /** * Returns attachment object will be added to the session's context upon * initialization. This object can be used to pass an initial processing * state to the protocol handler. * * @return attachment object. */ Object getAttachment(); /** * Determines whether the request has been completed (either successfully * or unsuccessfully). * * @return {@code true} if the request has been completed, * {@code false} if still pending. */ boolean isCompleted(); /** * Returns {@link IOSession} instance created as a result of this request * or {@code null} if the request is still pending. * * @return I/O session or {@code null} if the request is still pending. */ IOSession getSession(); /** * Returns {@link IOException} instance if the request could not be * successfully executed due to an I/O error or {@code null} if no * error occurred to this point. * * @return I/O exception or {@code null} if no error occurred to * this point. */ IOException getException(); /** * Waits for completion of this session request. * * @throws InterruptedException in case the execution process was * interrupted. */ void waitFor() throws InterruptedException; /** * Sets connect timeout value in milliseconds. * * @param timeout connect timeout value in milliseconds. */ void setConnectTimeout(int timeout); /** * Returns connect timeout value in milliseconds. * * @return connect timeout value in milliseconds. */ int getConnectTimeout(); /** * Cancels the request. Invocation of this method will set the status of * the request to completed and will unblock threads blocked in * the {{@link #waitFor()}} method. */ void cancel(); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactor.java0100644 0000000 0000000 00000006547 12613456026 031262 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.io.IOException; /** * 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 implementing * the Reactor pattern. *

* 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. * * @since 4.0 */ public interface IOReactor { /** * Returns the current status of the reactor. * * @return reactor status. */ IOReactorStatus getStatus(); /** * Starts the reactor and initiates the dispatch of I/O event notifications * to the given {@link IOEventDispatch}. * * @param eventDispatch the I/O event dispatch. * @throws IOException in case of an I/O error. */ void execute(IOEventDispatch eventDispatch) throws IOException; /** * Initiates shutdown of the reactor and blocks approximately for the given * period of time in milliseconds waiting for the reactor to terminate all * active connections, to shut down itself and to release system resources * it currently holds. * * @param waitMs wait time in milliseconds. * @throws IOException in case of an I/O error. */ void shutdown(long waitMs) throws IOException; /** * Initiates shutdown of the reactor and blocks for a default period of * time waiting for the reactor to terminate all active connections, to shut * down itself and to release system resources it currently holds. It is * up to individual implementations to decide for how long this method can * remain blocked. * * @throws IOException in case of an I/O error. */ void shutdown() throws IOException; } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/EventMask.java0100644 0000000 0000000 00000003264 12613456026 031321 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.nio.channels.SelectionKey; /** * Type of I/O event notifications I/O sessions can declare interest in. * * @since 4.0 */ public interface EventMask { /** * Interest in data input. */ public static final int READ = SelectionKey.OP_READ; /** * Interest in data output. */ public static final int WRITE = SelectionKey.OP_WRITE; /** * Interest in data input/output. */ public static final int READ_WRITE = READ | WRITE; } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ListenerEndpoint.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ListenerEndpoint.ja0100644 0000000 0000000 00000004705 12613456026 032364 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor; import java.io.IOException; import java.net.SocketAddress; /** * ListenerEndpoint interface represents an endpoint used by an I/O reactor * to listen for incoming connection from remote clients. * * @since 4.0 */ public interface ListenerEndpoint { /** * Returns the socket address of this endpoint. * * @return socket address. */ SocketAddress getAddress(); /** * Returns an instance of {@link IOException} thrown during initialization * of this endpoint or {@code null}, if initialization was successful. * * @return I/O exception object or {@code null}. */ IOException getException(); /** * Waits for completion of initialization process of this endpoint. * * @throws InterruptedException in case the initialization process was * interrupted. */ void waitFor() throws InterruptedException; /** * Determines if this endpoint has been closed and is no longer listens * for incoming connections. * * @return {@code true} if the endpoint has been closed, * {@code false} otherwise. */ boolean isClosed(); /** * Closes this endpoint. The endpoint will stop accepting incoming * connection. */ void close(); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/0040755 0000000 0000000 00000000000 12613456026 027360 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000166 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/SSLBufferManagementStrategy.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/SSLBufferManage0100644 0000000 0000000 00000003125 12613456026 032205 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor.ssl; /** * Encapsulates logic to manager SSL input/output buffers. */ public interface SSLBufferManagementStrategy { /** * Creates a {@link SSLBuffer} of {@code size}. * @param size size of the buffer to create * @return constructed buffer * @throws IllegalArgumentException if {@code size} is not greater than {@code 0} */ SSLBuffer constructBuffer(int size); } ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/SSLSetupHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/SSLSetupHandler0100644 0000000 0000000 00000005035 12613456026 032263 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor.ssl; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import org.apache.http.nio.reactor.IOSession; /** * Callback interface that can be used to customize various aspects of * the TLS/SSl protocol. * * @since 4.2 */ public interface SSLSetupHandler { /** * Triggered when the SSL connection is being initialized. Custom handlers * can use this callback to customize properties of the {@link SSLEngine} * used to establish the SSL session. * * @param sslengine the SSL engine. * @throws SSLException if case of SSL protocol error. */ //FIXME: fix type void initalize(SSLEngine sslengine) throws SSLException; /** * Triggered when the SSL connection has been established and initial SSL * handshake has been successfully completed. Custom handlers can use * this callback to verify properties of the {@link SSLSession}. * For instance this would be the right place to enforce SSL cipher * strength, validate certificate chain and do hostname checks. * * @param iosession the underlying IOSession for the SSL connection. * @param sslsession newly created SSL session. * @throws SSLException if case of SSL protocol error. */ void verify(IOSession iosession, SSLSession sslsession) throws SSLException; } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/package-info.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/package-info.ja0100644 0000000 0000000 00000002423 12613456026 032216 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ /** * TLS/SSL support for asynchronous, event driven communication. */ package org.apache.http.nio.reactor.ssl; ././@LongLink0100644 0000000 0000000 00000000200 12613460517 011630 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/ReleasableSSLBufferManagementStrategy.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/ReleasableSSLBu0100644 0000000 0000000 00000004575 12613456026 032223 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor.ssl; import java.nio.ByteBuffer; import org.apache.http.util.Args; /** * A {@link SSLBufferManagementStrategy} that releases the underlying buffer when deactivated. */ public class ReleasableSSLBufferManagementStrategy implements SSLBufferManagementStrategy { @Override public SSLBuffer constructBuffer(final int size) { return new InternalBuffer(size); } private static final class InternalBuffer implements SSLBuffer { private ByteBuffer wrapped; private final int length; public InternalBuffer(final int size) { Args.positive(size, "size"); this.length = size; } @Override public ByteBuffer acquire() { if (wrapped != null) { return wrapped; } wrapped = ByteBuffer.allocate(length); return wrapped; } @Override public void release() { wrapped = null; } @Override public boolean isAcquired() { return wrapped != null; } @Override public boolean hasData() { return wrapped != null && wrapped.position() > 0; } } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/SSLBuffer.java0100644 0000000 0000000 00000004466 12613456026 032025 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor.ssl; import java.nio.ByteBuffer; /** * Managed internal SSL buffer. */ public interface SSLBuffer { /** * Allocates the resources required for this buffer, or returns the resources already allocated for this buffer. * Unless {@link #release() } is called, multiple invokations to this method must return the same * {@link java.nio.ByteBuffer}. * @return buffer */ ByteBuffer acquire(); /** * Releases the resources for this buffer. If the buffer has already been released, this method does nothing. */ void release(); /** * Tests to see if this buffer has been acquired. * @return {@code true} if the buffer is acquired, otherwise {@code false} */ boolean isAcquired(); /** * Tests to make sure that the buffer has been acquired and the underlying buffer has a position larger than * {@code 0}. Essentially the same as {@code isAquired() && acquire().position > 0}. * @return {@code true} if the buffer has been acquired and the underlying buffer's position is {@code > 0}, * otherwise {@code false} */ boolean hasData(); } ././@LongLink0100644 0000000 0000000 00000000177 12613460517 011645 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/PermanentSSLBufferManagementStrategy.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/PermanentSSLBuf0100644 0000000 0000000 00000004276 12613456026 032261 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor.ssl; import java.nio.ByteBuffer; import org.apache.http.util.Args; /** * A {@link SSLBufferManagementStrategy} that never releases the underlying buffer. */ public class PermanentSSLBufferManagementStrategy implements SSLBufferManagementStrategy { @Override public SSLBuffer constructBuffer(final int size) { return new InternalBuffer(size); } private static final class InternalBuffer implements SSLBuffer { private final ByteBuffer buffer; public InternalBuffer(final int size) { Args.positive(size, "size"); buffer = ByteBuffer.allocate(size); } @Override public ByteBuffer acquire() { return buffer; } @Override public void release() { // do nothing } @Override public boolean isAcquired() { return true; } @Override public boolean hasData() { return buffer.position() > 0; } } } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/SSLIOSession.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/SSLIOSession.ja0100644 0000000 0000000 00000065767 12613456026 032153 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.reactor.ssl; import java.io.IOException; import java.net.Socket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import org.apache.http.HttpHost; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.reactor.EventMask; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionBufferStatus; import org.apache.http.nio.reactor.SocketAccessor; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * {@code SSLIOSession} is a decorator class intended to transparently extend * an {@link IOSession} with transport layer security capabilities based on * the SSL/TLS protocol. *

* The resultant instance of {@code SSLIOSession} must be added to the original * I/O session as an attribute with the {@link #SESSION_KEY} key. *

 *  SSLContext sslcontext = SSLContext.getInstance("SSL");
 *  sslcontext.init(null, null, null);
 *  SSLIOSession sslsession = new SSLIOSession(
 *      iosession, SSLMode.CLIENT, sslcontext, null);
 *  iosession.setAttribute(SSLIOSession.SESSION_KEY, sslsession);
 * 
* * @since 4.2 */ @ThreadSafe public class SSLIOSession implements IOSession, SessionBufferStatus, SocketAccessor { /** * Name of the context attribute key, which can be used to obtain the * SSL session. */ public static final String SESSION_KEY = "http.session.ssl"; private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); private final IOSession session; private final SSLEngine sslEngine; private final SSLBuffer inEncrypted; private final SSLBuffer outEncrypted; private final SSLBuffer inPlain; private final SSLBuffer outPlain; private final InternalByteChannel channel; private final SSLSetupHandler handler; private int appEventMask; private SessionBufferStatus appBufferStatus; private boolean endOfStream; private volatile SSLMode sslMode; private volatile int status; private volatile boolean initialized; /** * Creates new instance of {@code SSLIOSession} class. The instances created uses a * {@link PermanentSSLBufferManagementStrategy} to manage its buffers. * * @param session I/O session to be decorated with the TLS/SSL capabilities. * @param sslMode SSL mode (client or server) * @param host original host (applicable in client mode only) * @param sslContext SSL context to use for this I/O session. * @param handler optional SSL setup handler. May be {@code null}. * * @since 4.4 */ public SSLIOSession( final IOSession session, final SSLMode sslMode, final HttpHost host, final SSLContext sslContext, final SSLSetupHandler handler) { this(session, sslMode, host, sslContext, handler, new PermanentSSLBufferManagementStrategy()); } /** * Creates new instance of {@code SSLIOSession} class. * * @param session I/O session to be decorated with the TLS/SSL capabilities. * @param sslMode SSL mode (client or server) * @param host original host (applicable in client mode only) * @param sslContext SSL context to use for this I/O session. * @param handler optional SSL setup handler. May be {@code null}. * @param bufferManagementStrategy buffer management strategy */ public SSLIOSession( final IOSession session, final SSLMode sslMode, final HttpHost host, final SSLContext sslContext, final SSLSetupHandler handler, final SSLBufferManagementStrategy bufferManagementStrategy) { super(); Args.notNull(session, "IO session"); Args.notNull(sslContext, "SSL context"); Args.notNull(bufferManagementStrategy, "Buffer management strategy"); this.session = session; this.sslMode = sslMode; this.appEventMask = session.getEventMask(); this.channel = new InternalByteChannel(); this.handler = handler; // Override the status buffer interface this.session.setBufferStatus(this); if (this.sslMode == SSLMode.CLIENT && host != null) { this.sslEngine = sslContext.createSSLEngine(host.getHostName(), host.getPort()); } else { this.sslEngine = sslContext.createSSLEngine(); } // Allocate buffers for network (encrypted) data final int netBuffersize = this.sslEngine.getSession().getPacketBufferSize(); this.inEncrypted = bufferManagementStrategy.constructBuffer(netBuffersize); this.outEncrypted = bufferManagementStrategy.constructBuffer(netBuffersize); // Allocate buffers for application (unencrypted) data final int appBuffersize = this.sslEngine.getSession().getApplicationBufferSize(); this.inPlain = bufferManagementStrategy.constructBuffer(appBuffersize); this.outPlain = bufferManagementStrategy.constructBuffer(appBuffersize); } /** * Creates new instance of {@code SSLIOSession} class. * * @param session I/O session to be decorated with the TLS/SSL capabilities. * @param sslMode SSL mode (client or server) * @param sslContext SSL context to use for this I/O session. * @param handler optional SSL setup handler. May be {@code null}. */ public SSLIOSession( final IOSession session, final SSLMode sslMode, final SSLContext sslContext, final SSLSetupHandler handler) { this(session, sslMode, null, sslContext, handler); } protected SSLSetupHandler getSSLSetupHandler() { return this.handler; } /** * Returns {@code true} is the session has been fully initialized, * {@code false} otherwise. */ public boolean isInitialized() { return this.initialized; } /** * Initializes the session in the given {@link SSLMode}. This method * invokes the {@link SSLSetupHandler#initalize(SSLEngine)} callback * if an instance of {@link SSLSetupHandler} was specified at * the construction time. * * @deprecated (4.3) SSL mode must be set at construction time. */ @Deprecated public synchronized void initialize(final SSLMode sslMode) throws SSLException { this.sslMode = sslMode; initialize(); } /** * Initializes the session. This method invokes the {@link * SSLSetupHandler#initalize(SSLEngine)} callback if an instance of * {@link SSLSetupHandler} was specified at the construction time. * * @throws SSLException in case of a SSL protocol exception. * @throws IllegalStateException if the session has already been initialized. */ public synchronized void initialize() throws SSLException { Asserts.check(!this.initialized, "SSL I/O session already initialized"); if (this.status >= IOSession.CLOSING) { return; } switch (this.sslMode) { case CLIENT: this.sslEngine.setUseClientMode(true); break; case SERVER: this.sslEngine.setUseClientMode(false); break; } if (this.handler != null) { this.handler.initalize(this.sslEngine); } this.initialized = true; this.sslEngine.beginHandshake(); this.inEncrypted.release(); this.outEncrypted.release(); this.inPlain.release(); this.outPlain.release(); doHandshake(); } public synchronized SSLSession getSSLSession() { return this.sslEngine.getSession(); } // A works-around for exception handling craziness in Sun/Oracle's SSLEngine // implementation. // // sun.security.pkcs11.wrapper.PKCS11Exception is re-thrown as // plain RuntimeException in sun.security.ssl.Handshaker#checkThrown private SSLException convert(final RuntimeException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } return new SSLException(cause); } private SSLEngineResult doWrap(final ByteBuffer src, final ByteBuffer dst) throws SSLException { try { return this.sslEngine.wrap(src, dst); } catch (final RuntimeException ex) { throw convert(ex); } } private SSLEngineResult doUnwrap(final ByteBuffer src, final ByteBuffer dst) throws SSLException { try { return this.sslEngine.unwrap(src, dst); } catch (final RuntimeException ex) { throw convert(ex); } } private void doRunTask() throws SSLException { try { final Runnable r = this.sslEngine.getDelegatedTask(); if (r != null) { r.run(); } } catch (final RuntimeException ex) { throw convert(ex); } } private void doHandshake() throws SSLException { boolean handshaking = true; SSLEngineResult result = null; while (handshaking) { switch (this.sslEngine.getHandshakeStatus()) { case NEED_WRAP: // Generate outgoing handshake data // Acquire buffers ByteBuffer outPlainBuf = this.outPlain.acquire(); final ByteBuffer outEncryptedBuf = this.outEncrypted.acquire(); // Perform operations outPlainBuf.flip(); result = doWrap(outPlainBuf, outEncryptedBuf); outPlainBuf.compact(); // Release outPlain if empty if (outPlainBuf.position() == 0) { this.outPlain.release(); outPlainBuf = null; } if (result.getStatus() != Status.OK) { handshaking = false; } break; case NEED_UNWRAP: // Process incoming handshake data // Acquire buffers ByteBuffer inEncryptedBuf = this.inEncrypted.acquire(); ByteBuffer inPlainBuf = this.inPlain.acquire(); // Perform operations inEncryptedBuf.flip(); result = doUnwrap(inEncryptedBuf, inPlainBuf); inEncryptedBuf.compact(); try { if (!inEncryptedBuf.hasRemaining() && result.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) { throw new SSLException("Input buffer is full"); } } finally { // Release inEncrypted if empty if (inEncryptedBuf.position() == 0) { this.inEncrypted.release(); inEncryptedBuf = null; } } if (this.status >= IOSession.CLOSING) { this.inPlain.release(); inPlainBuf = null; } if (result.getStatus() != Status.OK) { handshaking = false; } break; case NEED_TASK: doRunTask(); break; case NOT_HANDSHAKING: handshaking = false; break; case FINISHED: break; } } // The SSLEngine has just finished handshaking. This value is only generated by a call // to SSLEngine.wrap()/unwrap() when that call finishes a handshake. // It is never generated by SSLEngine.getHandshakeStatus(). if (result != null && result.getHandshakeStatus() == HandshakeStatus.FINISHED) { if (this.handler != null) { this.handler.verify(this.session, this.sslEngine.getSession()); } } } private void updateEventMask() { // Graceful session termination if (this.status == CLOSING && this.sslEngine.isOutboundDone() && (this.endOfStream || this.sslEngine.isInboundDone())) { this.status = CLOSED; } // Abnormal session termination if (this.status == ACTIVE && this.endOfStream && this.sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) { this.status = CLOSED; } if (this.status == CLOSED) { this.session.close(); return; } // Need to toggle the event mask for this channel? final int oldMask = this.session.getEventMask(); int newMask = oldMask; switch (this.sslEngine.getHandshakeStatus()) { case NEED_WRAP: newMask = EventMask.READ_WRITE; break; case NEED_UNWRAP: newMask = EventMask.READ; break; case NOT_HANDSHAKING: newMask = this.appEventMask; break; case NEED_TASK: break; case FINISHED: break; } // Do we have encrypted data ready to be sent? if (this.outEncrypted.hasData()) { newMask = newMask | EventMask.WRITE; } // Update the mask if necessary if (oldMask != newMask) { this.session.setEventMask(newMask); } } private int sendEncryptedData() throws IOException { if (!this.outEncrypted.hasData()) { // If the buffer isn't acquired or is empty, call write() with an empty buffer. // This will ensure that tests performed by write() still take place without // having to acquire and release an empty buffer (e.g. connection closed, // interrupted thread, etc..) return this.session.channel().write(EMPTY_BUFFER); } // Acquire buffer final ByteBuffer outEncryptedBuf = this.outEncrypted.acquire(); // Perform operation outEncryptedBuf.flip(); final int bytesWritten = this.session.channel().write(outEncryptedBuf); outEncryptedBuf.compact(); // Release if empty if (outEncryptedBuf.position() == 0) { this.outEncrypted.release(); } return bytesWritten; } private int receiveEncryptedData() throws IOException { if (this.endOfStream) { return -1; } // Acquire buffer final ByteBuffer inEncryptedBuf = this.inEncrypted.acquire(); // Perform operation final int ret = this.session.channel().read(inEncryptedBuf); // Release if empty if (inEncryptedBuf.position() == 0) { this.inEncrypted.release(); } return ret; } private boolean decryptData() throws SSLException { boolean decrypted = false; while (this.inEncrypted.hasData()) { // Get buffers final ByteBuffer inEncryptedBuf = this.inEncrypted.acquire(); final ByteBuffer inPlainBuf = this.inPlain.acquire(); // Perform operations inEncryptedBuf.flip(); final SSLEngineResult result = doUnwrap(inEncryptedBuf, inPlainBuf); inEncryptedBuf.compact(); try { if (!inEncryptedBuf.hasRemaining() && result.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) { throw new SSLException("Input buffer is full"); } if (result.getStatus() == Status.OK) { decrypted = true; } else { break; } if (result.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) { break; } if (this.endOfStream) { break; } } finally { // Release inEncrypted if empty if (this.inEncrypted.acquire().position() == 0) { this.inEncrypted.release(); } } } return decrypted; } /** * Reads encrypted data and returns whether the channel associated with * this session has any decrypted inbound data available for reading. * * @throws IOException in case of an I/O error. */ public synchronized boolean isAppInputReady() throws IOException { do { final int bytesRead = receiveEncryptedData(); if (bytesRead == -1) { this.endOfStream = true; } doHandshake(); final HandshakeStatus status = this.sslEngine.getHandshakeStatus(); if (status == HandshakeStatus.NOT_HANDSHAKING || status == HandshakeStatus.FINISHED) { decryptData(); } } while (this.sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_TASK); // Some decrypted data is available or at the end of stream return (this.appEventMask & SelectionKey.OP_READ) > 0 && (this.inPlain.hasData() || (this.appBufferStatus != null && this.appBufferStatus.hasBufferedInput()) || (this.endOfStream && this.status == ACTIVE)); } /** * Returns whether the channel associated with this session is ready to * accept outbound unecrypted data for writing. * * @throws IOException - not thrown currently */ public synchronized boolean isAppOutputReady() throws IOException { return (this.appEventMask & SelectionKey.OP_WRITE) > 0 && this.status == ACTIVE && this.sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING; } /** * Executes inbound SSL transport operations. * * @throws IOException - not thrown currently */ public synchronized void inboundTransport() throws IOException { updateEventMask(); } /** * Sends encrypted data and executes outbound SSL transport operations. * * @throws IOException in case of an I/O error. */ public synchronized void outboundTransport() throws IOException { sendEncryptedData(); doHandshake(); updateEventMask(); } /** * Returns whether the session will produce any more inbound data. */ public synchronized boolean isInboundDone() { return this.sslEngine.isInboundDone(); } /** * Returns whether the session will accept any more outbound data. */ public synchronized boolean isOutboundDone() { return this.sslEngine.isOutboundDone(); } private synchronized int writePlain(final ByteBuffer src) throws SSLException { Args.notNull(src, "Byte buffer"); if (this.status != ACTIVE) { return -1; } if (this.outPlain.hasData()) { // Acquire buffers ByteBuffer outPlainBuf = this.outPlain.acquire(); final ByteBuffer outEncryptedBuf = this.outEncrypted.acquire(); // Perform operations outPlainBuf.flip(); doWrap(outPlainBuf, outEncryptedBuf); outPlainBuf.compact(); // Release outPlain if empty if (outPlainBuf.position() == 0) { this.outPlain.release(); outPlainBuf = null; } } if (!this.outPlain.hasData()) { final ByteBuffer outEncryptedBuf = this.outEncrypted.acquire(); final SSLEngineResult result = doWrap(src, outEncryptedBuf); if (result.getStatus() == Status.CLOSED) { this.status = CLOSED; } return result.bytesConsumed(); } else { return 0; } } private synchronized int readPlain(final ByteBuffer dst) { Args.notNull(dst, "Byte buffer"); if (this.inPlain.hasData()) { // Acquire buffer ByteBuffer inPlainBuf = this.inPlain.acquire(); // Perform opertaions inPlainBuf.flip(); final int n = Math.min(inPlainBuf.remaining(), dst.remaining()); for (int i = 0; i < n; i++) { dst.put(inPlainBuf.get()); } inPlainBuf.compact(); // Release if empty if (inPlainBuf.position() == 0) { this.inPlain.release(); inPlainBuf = null; } return n; } else { if (this.endOfStream) { return -1; } else { return 0; } } } @Override public synchronized void close() { if (this.status >= CLOSING) { return; } // deactivating buffers in here causes failed tests this.status = CLOSING; this.sslEngine.closeOutbound(); updateEventMask(); } @Override public synchronized void shutdown() { if (this.status == CLOSED) { return; } this.inEncrypted.release(); this.outEncrypted.release(); this.inPlain.release(); this.outPlain.release(); this.status = CLOSED; this.session.shutdown(); } @Override public int getStatus() { return this.status; } @Override public boolean isClosed() { return this.status >= CLOSING || this.session.isClosed(); } @Override public ByteChannel channel() { return this.channel; } @Override public SocketAddress getLocalAddress() { return this.session.getLocalAddress(); } @Override public SocketAddress getRemoteAddress() { return this.session.getRemoteAddress(); } @Override public synchronized int getEventMask() { return this.appEventMask; } @Override public synchronized void setEventMask(final int ops) { this.appEventMask = ops; updateEventMask(); } @Override public synchronized void setEvent(final int op) { this.appEventMask = this.appEventMask | op; updateEventMask(); } @Override public synchronized void clearEvent(final int op) { this.appEventMask = this.appEventMask & ~op; updateEventMask(); } @Override public int getSocketTimeout() { return this.session.getSocketTimeout(); } @Override public void setSocketTimeout(final int timeout) { this.session.setSocketTimeout(timeout); } @Override public synchronized boolean hasBufferedInput() { return (this.appBufferStatus != null && this.appBufferStatus.hasBufferedInput()) || this.inEncrypted.hasData() || this.inPlain.hasData(); } @Override public synchronized boolean hasBufferedOutput() { return (this.appBufferStatus != null && this.appBufferStatus.hasBufferedOutput()) || this.outEncrypted.hasData() || this.outPlain.hasData(); } @Override public synchronized void setBufferStatus(final SessionBufferStatus status) { this.appBufferStatus = status; } @Override public Object getAttribute(final String name) { return this.session.getAttribute(name); } @Override public Object removeAttribute(final String name) { return this.session.removeAttribute(name); } @Override public void setAttribute(final String name, final Object obj) { this.session.setAttribute(name, obj); } private static void formatOps(final StringBuilder buffer, final int ops) { if ((ops & SelectionKey.OP_READ) > 0) { buffer.append('r'); } if ((ops & SelectionKey.OP_WRITE) > 0) { buffer.append('w'); } } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append(this.session); buffer.append("["); switch (this.status) { case ACTIVE: buffer.append("ACTIVE"); break; case CLOSING: buffer.append("CLOSING"); break; case CLOSED: buffer.append("CLOSED"); break; } buffer.append("]["); formatOps(buffer, this.appEventMask); buffer.append("]["); buffer.append(this.sslEngine.getHandshakeStatus()); if (this.sslEngine.isInboundDone()) { buffer.append("][inbound done]["); } if (this.sslEngine.isOutboundDone()) { buffer.append("][outbound done]["); } if (this.endOfStream) { buffer.append("][EOF]["); } buffer.append("]["); buffer.append(!this.inEncrypted.hasData() ? 0 : inEncrypted.acquire().position()); buffer.append("]["); buffer.append(!this.inPlain.hasData() ? 0 : inPlain.acquire().position()); buffer.append("]["); buffer.append(!this.outEncrypted.hasData() ? 0 : outEncrypted.acquire().position()); buffer.append("]["); buffer.append(!this.outPlain.hasData() ? 0 : outPlain.acquire().position()); buffer.append("]"); return buffer.toString(); } @Override public Socket getSocket(){ if (this.session instanceof SocketAccessor){ return ((SocketAccessor) this.session).getSocket(); } else { return null; } } private class InternalByteChannel implements ByteChannel { @Override public int write(final ByteBuffer src) throws IOException { return SSLIOSession.this.writePlain(src); } @Override public int read(final ByteBuffer dst) throws IOException { return SSLIOSession.this.readPlain(dst); } @Override public void close() throws IOException { SSLIOSession.this.close(); } @Override public boolean isOpen() { return !SSLIOSession.this.isClosed(); } } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ssl/SSLMode.java0100644 0000000 0000000 00000002422 12613456026 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.nio.reactor.ssl; /** * @since 4.2 */ public enum SSLMode { CLIENT, SERVER } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/0040755 0000000 0000000 00000000000 12613456024 025272 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/0040755 0000000 0000000 00000000000 12613456025 026060 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000162 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/NHttpClientEventHandlerAdaptor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/NHttpClientEventHandle0100644 0000000 0000000 00000007131 12613456025 032314 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientEventHandler; import org.apache.http.nio.NHttpClientHandler; /** * @deprecated (4.2) */ @Deprecated class NHttpClientEventHandlerAdaptor implements NHttpClientEventHandler { private final NHttpClientHandler handler; public NHttpClientEventHandlerAdaptor(final NHttpClientHandler handler) { super(); this.handler = handler; } @Override public void connected(final NHttpClientConnection conn, final Object attachment) { this.handler.connected(conn, attachment); } @Override public void requestReady( final NHttpClientConnection conn) throws IOException, HttpException { this.handler.requestReady(conn); } @Override public void responseReceived( final NHttpClientConnection conn) throws IOException, HttpException { this.handler.responseReceived(conn); } @Override public void inputReady( final NHttpClientConnection conn, final ContentDecoder decoder) throws IOException, HttpException { this.handler.inputReady(conn, decoder); } @Override public void outputReady( final NHttpClientConnection conn, final ContentEncoder encoder) throws IOException, HttpException { this.handler.outputReady(conn, encoder); } @Override public void exception(final NHttpClientConnection conn, final Exception ex) { if (ex instanceof HttpException) { this.handler.exception(conn, (HttpException) ex); } else if (ex instanceof IOException) { this.handler.exception(conn, (IOException) ex); } else { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new Error("Unexpected exception: ", ex); } } } @Override public void endOfInput(final NHttpClientConnection conn) throws IOException { conn.close(); } @Override public void timeout(final NHttpClientConnection conn) { this.handler.timeout(conn); } @Override public void closed(final NHttpClientConnection conn) { this.handler.closed(conn); } } ././@LongLink0100644 0000000 0000000 00000000146 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/SessionHttpContext.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/SessionHttpContext.jav0100644 0000000 0000000 00000003555 12613456025 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.nio; import org.apache.http.nio.reactor.IOSession; import org.apache.http.protocol.HttpContext; class SessionHttpContext implements HttpContext { private final IOSession iosession; public SessionHttpContext(final IOSession iosession) { super(); this.iosession = iosession; } @Override public Object getAttribute(final String id) { return this.iosession.getAttribute(id); } @Override public Object removeAttribute(final String id) { return this.iosession.removeAttribute(id); } @Override public void setAttribute(final String id, final Object obj) { this.iosession.setAttribute(id, obj); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/NHttpConnectionBase.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/NHttpConnectionBase.ja0100644 0000000 0000000 00000054243 12613456025 032251 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import org.apache.http.ConnectionClosedException; import org.apache.http.Consts; import org.apache.http.Header; 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.HttpRequest; import org.apache.http.HttpResponse; 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.HttpConnectionMetricsImpl; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.codecs.ChunkDecoder; import org.apache.http.impl.nio.codecs.ChunkEncoder; import org.apache.http.impl.nio.codecs.IdentityDecoder; import org.apache.http.impl.nio.codecs.IdentityEncoder; import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder; import org.apache.http.impl.nio.codecs.LengthDelimitedEncoder; import org.apache.http.impl.nio.reactor.SessionInputBufferImpl; import org.apache.http.impl.nio.reactor.SessionOutputBufferImpl; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.reactor.EventMask; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionBufferStatus; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.reactor.SocketAccessor; import org.apache.http.nio.util.ByteBufferAllocator; 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.protocol.HttpContext; import org.apache.http.util.Args; import org.apache.http.util.CharsetUtils; import org.apache.http.util.NetUtils; /** * This class serves as a base for all {@link NHttpConnection} implementations and provides * functionality common to both client and server HTTP connections. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public class NHttpConnectionBase implements NHttpConnection, HttpInetConnection, SessionBufferStatus, SocketAccessor { protected final ContentLengthStrategy incomingContentStrategy; protected final ContentLengthStrategy outgoingContentStrategy; protected final SessionInputBufferImpl inbuf; protected final SessionOutputBufferImpl outbuf; private final int fragmentSizeHint; private final MessageConstraints constraints; protected final HttpTransportMetricsImpl inTransportMetrics; protected final HttpTransportMetricsImpl outTransportMetrics; protected final HttpConnectionMetricsImpl connMetrics; protected HttpContext context; protected IOSession session; protected SocketAddress remote; protected volatile ContentDecoder contentDecoder; protected volatile boolean hasBufferedInput; protected volatile ContentEncoder contentEncoder; protected volatile boolean hasBufferedOutput; protected volatile HttpRequest request; protected volatile HttpResponse response; protected volatile int status; /** * Creates a new instance of this class given the underlying I/O session. * * @param session the underlying I/O session. * @param allocator byte buffer allocator. * @param params HTTP parameters. * * @deprecated (4.3) use * {@link NHttpConnectionBase#NHttpConnectionBase(IOSession, int, int, ByteBufferAllocator, * CharsetDecoder, CharsetEncoder, ContentLengthStrategy, ContentLengthStrategy)} */ @Deprecated public NHttpConnectionBase( final IOSession session, final ByteBufferAllocator allocator, final HttpParams params) { super(); Args.notNull(session, "I/O session"); Args.notNull(params, "HTTP params"); int buffersize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1); if (buffersize <= 0) { buffersize = 4096; } int linebuffersize = buffersize; if (linebuffersize > 512) { linebuffersize = 512; } CharsetDecoder decoder = null; CharsetEncoder encoder = null; Charset charset = CharsetUtils.lookup( (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET)); if (charset != null) { charset = Consts.ASCII; decoder = charset.newDecoder(); encoder = charset.newEncoder(); final CodingErrorAction malformedCharAction = (CodingErrorAction) params.getParameter( CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION); final CodingErrorAction unmappableCharAction = (CodingErrorAction) params.getParameter( CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION); decoder.onMalformedInput(malformedCharAction).onUnmappableCharacter(unmappableCharAction); encoder.onMalformedInput(malformedCharAction).onUnmappableCharacter(unmappableCharAction); } this.inbuf = new SessionInputBufferImpl(buffersize, linebuffersize, decoder, allocator); this.outbuf = new SessionOutputBufferImpl(buffersize, linebuffersize, encoder, allocator); this.fragmentSizeHint = buffersize; this.constraints = MessageConstraints.DEFAULT; this.incomingContentStrategy = createIncomingContentStrategy(); this.outgoingContentStrategy = createOutgoingContentStrategy(); this.inTransportMetrics = createTransportMetrics(); this.outTransportMetrics = createTransportMetrics(); this.connMetrics = createConnectionMetrics( this.inTransportMetrics, this.outTransportMetrics); setSession(session); this.status = ACTIVE; } /** * Creates new instance NHttpConnectionBase given the underlying I/O session. * * @param session the underlying I/O session. * @param buffersize buffer size. Must be a positive number. * @param fragmentSizeHint fragment size hint. * @param allocator memory allocator. * If {@code null} {@link org.apache.http.nio.util.HeapByteBufferAllocator#INSTANCE} * will be used. * @param chardecoder decoder to be used for decoding HTTP protocol elements. * If {@code null} simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If {@code null} * {@link LaxContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If {@code null} * {@link StrictContentLengthStrategy#INSTANCE} will be used. * * @since 4.4 */ protected NHttpConnectionBase( final IOSession session, final int buffersize, final int fragmentSizeHint, final ByteBufferAllocator allocator, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy) { Args.notNull(session, "I/O session"); Args.positive(buffersize, "Buffer size"); int linebuffersize = buffersize; if (linebuffersize > 512) { linebuffersize = 512; } this.inbuf = new SessionInputBufferImpl(buffersize, linebuffersize, chardecoder, allocator); this.outbuf = new SessionOutputBufferImpl(buffersize, linebuffersize, charencoder, allocator); this.fragmentSizeHint = fragmentSizeHint >= 0 ? fragmentSizeHint : buffersize; this.inTransportMetrics = new HttpTransportMetricsImpl(); this.outTransportMetrics = new HttpTransportMetricsImpl(); this.connMetrics = new HttpConnectionMetricsImpl(this.inTransportMetrics, this.outTransportMetrics); this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy : LaxContentLengthStrategy.INSTANCE; this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy : StrictContentLengthStrategy.INSTANCE; setSession(session); this.status = ACTIVE; } /** * Creates new instance NHttpConnectionBase given the underlying I/O session. * * @param session the underlying I/O session. * @param buffersize buffer size. Must be a positive number. * @param fragmentSizeHint fragment size hint. * @param allocator memory allocator. * If {@code null} {@link org.apache.http.nio.util.HeapByteBufferAllocator#INSTANCE} * will be used. * @param chardecoder decoder to be used for decoding HTTP protocol elements. * If {@code null} simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. * @param incomingContentStrategy incoming content length strategy. If {@code null} * {@link LaxContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If {@code null} * {@link StrictContentLengthStrategy#INSTANCE} will be used. * * @since 4.3 */ protected NHttpConnectionBase( final IOSession session, final int buffersize, final int fragmentSizeHint, final ByteBufferAllocator allocator, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy) { this(session, buffersize, fragmentSizeHint, allocator, chardecoder, charencoder, null, incomingContentStrategy, outgoingContentStrategy); } private void setSession(final IOSession session) { this.session = session; this.context = new SessionHttpContext(this.session); this.session.setBufferStatus(this); this.remote = this.session.getRemoteAddress(); } /** * Binds the connection to a different {@link IOSession}. This may be necessary * when the underlying I/O session gets upgraded with SSL/TLS encryption. * * @since 4.2 */ protected void bind(final IOSession session) { Args.notNull(session, "I/O session"); setSession(session); } /** * @since 4.2 * * @deprecated (4.3) use constructor. */ @Deprecated protected ContentLengthStrategy createIncomingContentStrategy() { return new LaxContentLengthStrategy(); } /** * @since 4.2 * * @deprecated (4.3) use constructor. */ @Deprecated protected ContentLengthStrategy createOutgoingContentStrategy() { return new StrictContentLengthStrategy(); } /** * @since 4.1 * * @deprecated (4.3) no longer used. */ @Deprecated protected HttpTransportMetricsImpl createTransportMetrics() { return new HttpTransportMetricsImpl(); } /** * @since 4.1 * * @deprecated (4.3) use decorator to add additional metrics. */ @Deprecated protected HttpConnectionMetricsImpl createConnectionMetrics( final HttpTransportMetrics inTransportMetric, final HttpTransportMetrics outTransportMetric) { return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric); } @Override public int getStatus() { return this.status; } @Override public HttpContext getContext() { return this.context; } @Override public HttpRequest getHttpRequest() { return this.request; } @Override public HttpResponse getHttpResponse() { return this.response; } @Override public void requestInput() { this.session.setEvent(EventMask.READ); } @Override public void requestOutput() { this.session.setEvent(EventMask.WRITE); } @Override public void suspendInput() { this.session.clearEvent(EventMask.READ); } @Override public void suspendOutput() { this.session.clearEvent(EventMask.WRITE); } /** * Initializes a specific {@link ContentDecoder} implementation based on the * properties of the given {@link HttpMessage} and generates an instance of * {@link HttpEntity} matching the properties of the content decoder. * * @param message the HTTP message. * @return HTTP entity. * @throws HttpException in case of an HTTP protocol violation. */ protected HttpEntity prepareDecoder(final HttpMessage message) throws HttpException { final BasicHttpEntity entity = new BasicHttpEntity(); final long len = this.incomingContentStrategy.determineLength(message); this.contentDecoder = createContentDecoder( len, this.session.channel(), this.inbuf, this.inTransportMetrics); if (len == ContentLengthStrategy.CHUNKED) { entity.setChunked(true); entity.setContentLength(-1); } else if (len == ContentLengthStrategy.IDENTITY) { entity.setChunked(false); entity.setContentLength(-1); } else { entity.setChunked(false); entity.setContentLength(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; } /** * Factory method for {@link ContentDecoder} instances. * * @param len content length, if known, {@link ContentLengthStrategy#CHUNKED} or * {@link ContentLengthStrategy#IDENTITY}, if unknown. * @param channel the session channel. * @param buffer the session buffer. * @param metrics transport metrics. * * @return content decoder. * * @since 4.1 */ protected ContentDecoder createContentDecoder( final long len, final ReadableByteChannel channel, final SessionInputBuffer buffer, final HttpTransportMetricsImpl metrics) { if (len == ContentLengthStrategy.CHUNKED) { return new ChunkDecoder(channel, buffer, this.constraints, metrics); } else if (len == ContentLengthStrategy.IDENTITY) { return new IdentityDecoder(channel, buffer, metrics); } else { return new LengthDelimitedDecoder(channel, buffer, metrics, len); } } /** * Initializes a specific {@link ContentEncoder} implementation based on the * properties of the given {@link HttpMessage}. * * @param message the HTTP message. * @throws HttpException in case of an HTTP protocol violation. */ protected void prepareEncoder(final HttpMessage message) throws HttpException { final long len = this.outgoingContentStrategy.determineLength(message); this.contentEncoder = createContentEncoder( len, this.session.channel(), this.outbuf, this.outTransportMetrics); } /** * Factory method for {@link ContentEncoder} instances. * * @param len content length, if known, {@link ContentLengthStrategy#CHUNKED} or * {@link ContentLengthStrategy#IDENTITY}, if unknown. * @param channel the session channel. * @param buffer the session buffer. * @param metrics transport metrics. * * @return content encoder. * * @since 4.1 */ protected ContentEncoder createContentEncoder( final long len, final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { if (len == ContentLengthStrategy.CHUNKED) { return new ChunkEncoder(channel, buffer, metrics, this.fragmentSizeHint); } else if (len == ContentLengthStrategy.IDENTITY) { return new IdentityEncoder(channel, buffer, metrics, this.fragmentSizeHint); } else { return new LengthDelimitedEncoder(channel, buffer, metrics, len, this.fragmentSizeHint); } } @Override public boolean hasBufferedInput() { return this.hasBufferedInput; } @Override public boolean hasBufferedOutput() { return this.hasBufferedOutput; } /** * Assets if the connection is still open. * * @throws ConnectionClosedException in case the connection has already * been closed. */ protected void assertNotClosed() throws ConnectionClosedException { if (this.status != ACTIVE) { throw new ConnectionClosedException("Connection is closed"); } } @Override public void close() throws IOException { if (this.status != ACTIVE) { return; } this.status = CLOSING; if (this.outbuf.hasData()) { this.session.setEvent(EventMask.WRITE); } else { this.session.close(); this.status = CLOSED; } } @Override public boolean isOpen() { return this.status == ACTIVE && !this.session.isClosed(); } @Override public boolean isStale() { return this.session.isClosed(); } @Override public InetAddress getLocalAddress() { final SocketAddress address = this.session.getLocalAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getAddress(); } else { return null; } } @Override public int getLocalPort() { final SocketAddress address = this.session.getLocalAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getPort(); } else { return -1; } } @Override public InetAddress getRemoteAddress() { final SocketAddress address = this.session.getRemoteAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getAddress(); } else { return null; } } @Override public int getRemotePort() { final SocketAddress address = this.session.getRemoteAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getPort(); } else { return -1; } } @Override public void setSocketTimeout(final int timeout) { this.session.setSocketTimeout(timeout); } @Override public int getSocketTimeout() { return this.session.getSocketTimeout(); } @Override public void shutdown() throws IOException { this.status = CLOSED; this.session.shutdown(); } @Override public HttpConnectionMetrics getMetrics() { return this.connMetrics; } @Override public String toString() { final SocketAddress remoteAddress = this.session.getRemoteAddress(); final SocketAddress localAddress = this.session.getLocalAddress(); if (remoteAddress != null && localAddress != null) { final StringBuilder buffer = new StringBuilder(); NetUtils.formatAddress(buffer, localAddress); buffer.append("<->"); NetUtils.formatAddress(buffer, remoteAddress); return buffer.toString(); } else { return "[Not bound]"; } } @Override public Socket getSocket() { if (this.session instanceof SocketAccessor) { return ((SocketAccessor) this.session).getSocket(); } else { return null; } } } ././@LongLink0100644 0000000 0000000 00000000162 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/NHttpServerEventHandlerAdaptor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/NHttpServerEventHandle0100644 0000000 0000000 00000007067 12613456025 032354 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServerEventHandler; import org.apache.http.nio.NHttpServiceHandler; /** * @deprecated (4.2) */ @Deprecated class NHttpServerEventHandlerAdaptor implements NHttpServerEventHandler { private final NHttpServiceHandler handler; public NHttpServerEventHandlerAdaptor(final NHttpServiceHandler handler) { super(); this.handler = handler; } @Override public void connected(final NHttpServerConnection conn) { this.handler.connected(conn); } @Override public void responseReady( final NHttpServerConnection conn) throws IOException, HttpException { this.handler.responseReady(conn); } @Override public void requestReceived( final NHttpServerConnection conn) throws IOException, HttpException { this.handler.requestReceived(conn); } @Override public void inputReady( final NHttpServerConnection conn, final ContentDecoder decoder) throws IOException, HttpException { this.handler.inputReady(conn, decoder); } @Override public void outputReady( final NHttpServerConnection conn, final ContentEncoder encoder) throws IOException, HttpException { this.handler.outputReady(conn, encoder); } @Override public void exception(final NHttpServerConnection conn, final Exception ex) { if (ex instanceof HttpException) { this.handler.exception(conn, (HttpException) ex); } else if (ex instanceof IOException) { this.handler.exception(conn, (IOException) ex); } else { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new Error("Unexpected exception: ", ex); } } } @Override public void endOfInput(final NHttpServerConnection conn) throws IOException { conn.close(); } @Override public void timeout(final NHttpServerConnection conn) { this.handler.timeout(conn); } @Override public void closed(final NHttpServerConnection conn) { this.handler.closed(conn); } } ././@LongLink0100644 0000000 0000000 00000000163 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/SSLNHttpClientConnectionFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/SSLNHttpClientConnecti0100644 0000000 0000000 00000022540 12613456025 032244 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import javax.net.ssl.SSLContext; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.annotation.Immutable; import org.apache.http.config.ConnectionConfig; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.ConnSupport; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.codecs.DefaultHttpResponseParserFactory; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ssl.SSLIOSession; import org.apache.http.nio.reactor.ssl.SSLMode; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParamConfig; import org.apache.http.params.HttpParams; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.Args; /** * Default factory for SSL encrypted, non-blocking * {@link org.apache.http.nio.NHttpClientConnection}s. * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable public class SSLNHttpClientConnectionFactory implements NHttpConnectionFactory { public static final SSLNHttpClientConnectionFactory INSTANCE = new SSLNHttpClientConnectionFactory(); private final ContentLengthStrategy incomingContentStrategy; private final ContentLengthStrategy outgoingContentStrategy; private final NHttpMessageParserFactory responseParserFactory; private final NHttpMessageWriterFactory requestWriterFactory; private final ByteBufferAllocator allocator; private final SSLContext sslcontext; private final SSLSetupHandler sslHandler; private final ConnectionConfig cconfig; /** * @deprecated (4.3) use {@link * SSLNHttpClientConnectionFactory#SSLNHttpClientConnectionFactory(SSLContext, * SSLSetupHandler, NHttpMessageParserFactory, NHttpMessageWriterFactory, * ByteBufferAllocator, ConnectionConfig)} */ @Deprecated public SSLNHttpClientConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpResponseFactory responseFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(); Args.notNull(responseFactory, "HTTP response factory"); Args.notNull(allocator, "Byte buffer allocator"); Args.notNull(params, "HTTP parameters"); this.sslcontext = sslcontext != null ? sslcontext : SSLContexts.createSystemDefault(); this.sslHandler = sslHandler; this.allocator = allocator; this.incomingContentStrategy = null; this.outgoingContentStrategy = null; this.responseParserFactory = new DefaultHttpResponseParserFactory(null, responseFactory); this.requestWriterFactory = null; this.cconfig = HttpParamConfig.getConnectionConfig(params); } /** * @deprecated (4.3) use {@link * SSLNHttpClientConnectionFactory#SSLNHttpClientConnectionFactory(SSLContext, * SSLSetupHandler, ConnectionConfig)} */ @Deprecated public SSLNHttpClientConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { this(sslcontext, sslHandler, DefaultHttpResponseFactory.INSTANCE, HeapByteBufferAllocator.INSTANCE, params); } /** * @deprecated (4.3) use {@link * SSLNHttpClientConnectionFactory#SSLNHttpClientConnectionFactory(ConnectionConfig)} */ @Deprecated public SSLNHttpClientConnectionFactory(final HttpParams params) { this(null, null, params); } /** * @since 4.3 */ public SSLNHttpClientConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final NHttpMessageParserFactory responseParserFactory, final NHttpMessageWriterFactory requestWriterFactory, final ByteBufferAllocator allocator, final ConnectionConfig cconfig) { super(); this.sslcontext = sslcontext != null ? sslcontext : SSLContexts.createSystemDefault(); this.sslHandler = sslHandler; this.incomingContentStrategy = incomingContentStrategy; this.outgoingContentStrategy = outgoingContentStrategy; this.responseParserFactory = responseParserFactory; this.requestWriterFactory = requestWriterFactory; this.allocator = allocator; this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; } /** * @since 4.3 */ public SSLNHttpClientConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final NHttpMessageParserFactory responseParserFactory, final NHttpMessageWriterFactory requestWriterFactory, final ByteBufferAllocator allocator, final ConnectionConfig cconfig) { this(sslcontext, sslHandler, null, null, responseParserFactory, requestWriterFactory, allocator, cconfig); } /** * @since 4.3 */ public SSLNHttpClientConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final NHttpMessageParserFactory responseParserFactory, final NHttpMessageWriterFactory requestWriterFactory, final ConnectionConfig cconfig) { this(sslcontext, sslHandler, null, null, responseParserFactory, requestWriterFactory, null, cconfig); } /** * @since 4.3 */ public SSLNHttpClientConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final ConnectionConfig config) { this(sslcontext, sslHandler, null, null, null, null, null, config); } /** * @since 4.3 */ public SSLNHttpClientConnectionFactory(final ConnectionConfig config) { this(null, null, null, null, null, null, null, config); } /** * @since 4.3 */ public SSLNHttpClientConnectionFactory() { this(null, null, null, null, null, null); } /** * @deprecated (4.3) no longer used. */ @Deprecated protected DefaultNHttpClientConnection createConnection( final IOSession session, final HttpResponseFactory responseFactory, final ByteBufferAllocator allocator, final HttpParams params) { return new DefaultNHttpClientConnection(session, responseFactory, allocator, params); } /** * @since 4.3 */ protected SSLIOSession createSSLIOSession( final IOSession iosession, final SSLContext sslcontext, final SSLSetupHandler sslHandler) { final SSLIOSession ssliosession = new SSLIOSession(iosession, SSLMode.CLIENT, sslcontext, sslHandler); return ssliosession; } @Override public DefaultNHttpClientConnection createConnection(final IOSession iosession) { final SSLIOSession ssliosession = createSSLIOSession(iosession, this.sslcontext, this.sslHandler); iosession.setAttribute(SSLIOSession.SESSION_KEY, ssliosession); return new DefaultNHttpClientConnection( ssliosession, this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), this.allocator, ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), this.incomingContentStrategy, this.outgoingContentStrategy, this.requestWriterFactory, this.responseParserFactory); } } ././@LongLink0100644 0000000 0000000 00000000163 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/SSLNHttpServerConnectionFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/SSLNHttpServerConnecti0100644 0000000 0000000 00000022343 12613456025 032275 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import javax.net.ssl.SSLContext; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; 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.impl.ConnSupport; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.impl.nio.codecs.DefaultHttpRequestParserFactory; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ssl.SSLIOSession; import org.apache.http.nio.reactor.ssl.SSLMode; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParamConfig; import org.apache.http.params.HttpParams; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.Args; /** * Default factory for SSL encrypted, non-blocking * {@link org.apache.http.nio.NHttpServerConnection}s. * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable public class SSLNHttpServerConnectionFactory implements NHttpConnectionFactory { private final SSLContext sslcontext; private final SSLSetupHandler sslHandler; private final ContentLengthStrategy incomingContentStrategy; private final ContentLengthStrategy outgoingContentStrategy; private final NHttpMessageParserFactory requestParserFactory; private final NHttpMessageWriterFactory responseWriterFactory; private final ByteBufferAllocator allocator; private final ConnectionConfig cconfig; /** * @deprecated (4.3) use {@link * SSLNHttpServerConnectionFactory#SSLNHttpServerConnectionFactory(SSLContext, * SSLSetupHandler, NHttpMessageParserFactory, NHttpMessageWriterFactory, * ByteBufferAllocator, ConnectionConfig)} */ @Deprecated public SSLNHttpServerConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpRequestFactory requestFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(); Args.notNull(requestFactory, "HTTP request factory"); Args.notNull(allocator, "Byte buffer allocator"); Args.notNull(params, "HTTP parameters"); this.sslcontext = sslcontext != null ? sslcontext : SSLContexts.createSystemDefault(); this.sslHandler = sslHandler; this.incomingContentStrategy = null; this.outgoingContentStrategy = null; this.requestParserFactory = new DefaultHttpRequestParserFactory(null, requestFactory); this.responseWriterFactory = null; this.allocator = allocator; this.cconfig = HttpParamConfig.getConnectionConfig(params); } /** * @deprecated (4.3) use {@link * SSLNHttpServerConnectionFactory#SSLNHttpServerConnectionFactory(SSLContext, * SSLSetupHandler, ConnectionConfig)} */ @Deprecated public SSLNHttpServerConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { this(sslcontext, sslHandler, DefaultHttpRequestFactory.INSTANCE, HeapByteBufferAllocator.INSTANCE, params); } /** * @deprecated (4.3) use {@link * SSLNHttpServerConnectionFactory#SSLNHttpServerConnectionFactory(ConnectionConfig)} */ @Deprecated public SSLNHttpServerConnectionFactory(final HttpParams params) { this(null, null, params); } /** * @since 4.3 */ public SSLNHttpServerConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final NHttpMessageParserFactory requestParserFactory, final NHttpMessageWriterFactory responseWriterFactory, final ByteBufferAllocator allocator, final ConnectionConfig cconfig) { super(); this.sslcontext = sslcontext != null ? sslcontext : SSLContexts.createSystemDefault(); this.sslHandler = sslHandler; this.incomingContentStrategy = incomingContentStrategy; this.outgoingContentStrategy = outgoingContentStrategy; this.requestParserFactory = requestParserFactory; this.responseWriterFactory = responseWriterFactory; this.allocator = allocator; this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; } /** * @since 4.3 */ public SSLNHttpServerConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final NHttpMessageParserFactory requestParserFactory, final NHttpMessageWriterFactory responseWriterFactory, final ByteBufferAllocator allocator, final ConnectionConfig cconfig) { this(sslcontext, sslHandler, null, null, requestParserFactory, responseWriterFactory, allocator, cconfig); } /** * @since 4.3 */ public SSLNHttpServerConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final NHttpMessageParserFactory requestParserFactory, final NHttpMessageWriterFactory responseWriterFactory, final ConnectionConfig cconfig) { this(sslcontext, sslHandler, null, null, requestParserFactory, responseWriterFactory, null, cconfig); } /** * @since 4.3 */ public SSLNHttpServerConnectionFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final ConnectionConfig config) { this(sslcontext, sslHandler, null, null, null, null, null, config); } /** * @since 4.3 */ public SSLNHttpServerConnectionFactory(final ConnectionConfig config) { this(null, null, null, null, null, null, null, config); } /** * @since 4.3 */ public SSLNHttpServerConnectionFactory() { this(null, null, null, null, null, null, null, null); } /** * @deprecated (4.3) no longer used. */ @Deprecated protected DefaultNHttpServerConnection createConnection( final IOSession session, final HttpRequestFactory requestFactory, final ByteBufferAllocator allocator, final HttpParams params) { return new DefaultNHttpServerConnection(session, requestFactory, allocator, params); } /** * @since 4.3 */ protected SSLIOSession createSSLIOSession( final IOSession iosession, final SSLContext sslcontext, final SSLSetupHandler sslHandler) { final SSLIOSession ssliosession = new SSLIOSession(iosession, SSLMode.SERVER, sslcontext, sslHandler); return ssliosession; } @Override public DefaultNHttpServerConnection createConnection(final IOSession iosession) { final SSLIOSession ssliosession = createSSLIOSession(iosession, this.sslcontext, this.sslHandler); iosession.setAttribute(SSLIOSession.SESSION_KEY, ssliosession); return new DefaultNHttpServerConnection(ssliosession, this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), this.allocator, ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), this.incomingContentStrategy, this.outgoingContentStrategy, this.requestParserFactory, this.responseWriterFactory); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/package-info.java0100644 0000000 0000000 00000002452 12613456025 031247 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 asynchronous, * even driven communication. */ package org.apache.http.impl.nio; ././@LongLink0100644 0000000 0000000 00000000157 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultHttpServerIODispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultHttpServerIODis0100644 0000000 0000000 00000013671 12613456025 032313 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import javax.net.ssl.SSLContext; import org.apache.http.annotation.Immutable; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.nio.reactor.AbstractIODispatch; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.NHttpServerEventHandler; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default {@link org.apache.http.nio.reactor.IOEventDispatch} implementation * that supports both plain (non-encrypted) and SSL encrypted server side HTTP * connections. * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable // provided injected dependencies are immutable public class DefaultHttpServerIODispatch extends AbstractIODispatch { private final NHttpServerEventHandler handler; private final NHttpConnectionFactory connFactory; public DefaultHttpServerIODispatch( final NHttpServerEventHandler handler, final NHttpConnectionFactory connFactory) { super(); this.handler = Args.notNull(handler, "HTTP client handler"); this.connFactory = Args.notNull(connFactory, "HTTP server connection factory"); } /** * @deprecated (4.3) use {@link DefaultHttpServerIODispatch#DefaultHttpServerIODispatch( * NHttpServerEventHandler, ConnectionConfig)} */ @Deprecated public DefaultHttpServerIODispatch( final NHttpServerEventHandler handler, final HttpParams params) { this(handler, new DefaultNHttpServerConnectionFactory(params)); } /** * @deprecated (4.3) use {@link DefaultHttpServerIODispatch#DefaultHttpServerIODispatch( * NHttpServerEventHandler, SSLContext, SSLSetupHandler, ConnectionConfig)} */ @Deprecated public DefaultHttpServerIODispatch( final NHttpServerEventHandler handler, final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { this(handler, new SSLNHttpServerConnectionFactory(sslcontext, sslHandler, params)); } /** * @deprecated (4.3) use {@link DefaultHttpServerIODispatch#DefaultHttpServerIODispatch( * NHttpServerEventHandler, SSLContext, ConnectionConfig)} */ @Deprecated public DefaultHttpServerIODispatch( final NHttpServerEventHandler handler, final SSLContext sslcontext, final HttpParams params) { this(handler, sslcontext, null, params); } /** * @since 4.3 */ public DefaultHttpServerIODispatch(final NHttpServerEventHandler handler, final ConnectionConfig config) { this(handler, new DefaultNHttpServerConnectionFactory(config)); } /** * @since 4.3 */ public DefaultHttpServerIODispatch( final NHttpServerEventHandler handler, final SSLContext sslcontext, final SSLSetupHandler sslHandler, final ConnectionConfig config) { this(handler, new SSLNHttpServerConnectionFactory(sslcontext, sslHandler, config)); } /** * @since 4.3 */ public DefaultHttpServerIODispatch( final NHttpServerEventHandler handler, final SSLContext sslcontext, final ConnectionConfig config) { this(handler, new SSLNHttpServerConnectionFactory(sslcontext, null, config)); } @Override protected DefaultNHttpServerConnection createConnection(final IOSession session) { return this.connFactory.createConnection(session); } @Override protected void onConnected(final DefaultNHttpServerConnection conn) { try { this.handler.connected(conn); } catch (final Exception ex) { this.handler.exception(conn, ex); } } @Override protected void onClosed(final DefaultNHttpServerConnection conn) { this.handler.closed(conn); } @Override protected void onException(final DefaultNHttpServerConnection conn, final IOException ex) { this.handler.exception(conn, ex); } @Override protected void onInputReady(final DefaultNHttpServerConnection conn) { conn.consumeInput(this.handler); } @Override protected void onOutputReady(final DefaultNHttpServerConnection conn) { conn.produceOutput(this.handler); } @Override protected void onTimeout(final DefaultNHttpServerConnection conn) { try { this.handler.timeout(conn); } catch (final Exception ex) { this.handler.exception(conn, ex); } } } ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpServerConnection.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpServerConn0100644 0000000 0000000 00000035613 12613456025 032357 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import java.nio.channels.SelectionKey; 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.HttpRequestFactory; import org.apache.http.HttpResponse; 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.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.nio.codecs.DefaultHttpRequestParser; import org.apache.http.impl.nio.codecs.DefaultHttpRequestParserFactory; import org.apache.http.impl.nio.codecs.DefaultHttpResponseWriter; import org.apache.http.impl.nio.codecs.DefaultHttpResponseWriterFactory; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.NHttpServerEventHandler; import org.apache.http.nio.NHttpServerIOTarget; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.EventMask; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.params.HttpParamConfig; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default implementation of the {@link org.apache.http.nio.NHttpServerConnection} * interface. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public class DefaultNHttpServerConnection extends NHttpConnectionBase implements NHttpServerIOTarget { protected final NHttpMessageParser requestParser; protected final NHttpMessageWriter responseWriter; /** * Creates a new instance of this class given the underlying I/O session. * * @param session the underlying I/O session. * @param requestFactory HTTP request factory. * @param allocator byte buffer allocator. * @param params HTTP parameters. * * @deprecated (4.3) use {@link DefaultNHttpServerConnection#DefaultNHttpServerConnection( * IOSession, int, int, ByteBufferAllocator, CharsetDecoder, CharsetEncoder, * MessageConstraints, ContentLengthStrategy, ContentLengthStrategy, * NHttpMessageParserFactory, NHttpMessageWriterFactory)} */ @Deprecated public DefaultNHttpServerConnection( final IOSession session, final HttpRequestFactory requestFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(session, allocator, params); Args.notNull(requestFactory, "Request factory"); this.requestParser = createRequestParser(this.inbuf, requestFactory, params); this.responseWriter = createResponseWriter(this.outbuf, params); } /** * Creates new instance DefaultNHttpServerConnection given the underlying I/O session. * * @param session the underlying I/O session. * @param buffersize buffer size. Must be a positive number. * @param fragmentSizeHint fragment size hint. * @param allocator memory allocator. * If {@code null} {@link org.apache.http.nio.util.HeapByteBufferAllocator#INSTANCE} * will be used. * @param chardecoder decoder to be used for decoding HTTP protocol elements. * If {@code null} simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If {@code null} * {@link DisallowIdentityContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If {@code null} * {@link StrictContentLengthStrategy#INSTANCE} will be used. * @param requestParserFactory request parser factory. If {@code null} * {@link DefaultHttpRequestParserFactory#INSTANCE} will be used. * @param responseWriterFactory response writer factory. If {@code null} * {@link DefaultHttpResponseWriterFactory#INSTANCE} will be used. * * @since 4.3 */ public DefaultNHttpServerConnection( final IOSession session, final int buffersize, final int fragmentSizeHint, final ByteBufferAllocator allocator, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final NHttpMessageParserFactory requestParserFactory, final NHttpMessageWriterFactory responseWriterFactory) { super(session, buffersize, fragmentSizeHint, allocator, chardecoder, charencoder, constraints, incomingContentStrategy != null ? incomingContentStrategy : DisallowIdentityContentLengthStrategy.INSTANCE, outgoingContentStrategy != null ? outgoingContentStrategy : StrictContentLengthStrategy.INSTANCE); this.requestParser = (requestParserFactory != null ? requestParserFactory : DefaultHttpRequestParserFactory.INSTANCE).create(this.inbuf, constraints); this.responseWriter = (responseWriterFactory != null ? responseWriterFactory : DefaultHttpResponseWriterFactory.INSTANCE).create(this.outbuf); } /** * @since 4.3 */ public DefaultNHttpServerConnection( final IOSession session, final int buffersize, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints) { this(session, buffersize, buffersize, null, chardecoder, charencoder, constraints, null, null, null, null); } /** * @since 4.3 */ public DefaultNHttpServerConnection(final IOSession session, final int buffersize) { this(session, buffersize, buffersize, null, null, null, null, null, null, null, null); } /** * @deprecated (4.3) use constructor. */ @Override @Deprecated protected ContentLengthStrategy createIncomingContentStrategy() { return new DisallowIdentityContentLengthStrategy(new LaxContentLengthStrategy(0)); } /** * Creates an instance of {@link NHttpMessageParser} to be used * by this connection for parsing incoming {@link HttpRequest} messages. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpMessageParser} interface. * * @return HTTP response parser. * * @deprecated (4.3) use constructor. */ @Deprecated protected NHttpMessageParser createRequestParser( final SessionInputBuffer buffer, final HttpRequestFactory requestFactory, final HttpParams params) { final MessageConstraints constraints = HttpParamConfig.getMessageConstraints(params); return new DefaultHttpRequestParser(buffer, null, requestFactory, constraints); } /** * Creates an instance of {@link NHttpMessageWriter} to be used * by this connection for writing out outgoing {@link HttpResponse} * messages. *

* This method can be overridden by a super class in order to provide * a different implementation of the {@link NHttpMessageWriter} interface. * * @return HTTP response parser. * * @deprecated (4.3) use constructor. */ @Deprecated protected NHttpMessageWriter createResponseWriter( final SessionOutputBuffer buffer, final HttpParams params) { // override in derived class to specify a line formatter return new DefaultHttpResponseWriter(buffer, null); } /** * @since 4.2 */ protected void onRequestReceived(final HttpRequest request) { } /** * @since 4.2 */ protected void onResponseSubmitted(final HttpResponse response) { } @Override public void resetInput() { this.request = null; this.contentDecoder = null; this.requestParser.reset(); } @Override public void resetOutput() { this.response = null; this.contentEncoder = null; this.responseWriter.reset(); } public void consumeInput(final NHttpServerEventHandler handler) { if (this.status != ACTIVE) { this.session.clearEvent(EventMask.READ); return; } try { if (this.request == null) { int bytesRead; do { bytesRead = this.requestParser.fillBuffer(this.session.channel()); if (bytesRead > 0) { this.inTransportMetrics.incrementBytesTransferred(bytesRead); } this.request = this.requestParser.parse(); } while (bytesRead > 0 && this.request == null); if (this.request != null) { if (this.request instanceof HttpEntityEnclosingRequest) { // Receive incoming entity final HttpEntity entity = prepareDecoder(this.request); ((HttpEntityEnclosingRequest)this.request).setEntity(entity); } this.connMetrics.incrementRequestCount(); this.hasBufferedInput = this.inbuf.hasData(); onRequestReceived(this.request); handler.requestReceived(this); if (this.contentDecoder == null) { // No request entity is expected // Ready to receive a new request resetInput(); } } if (bytesRead == -1 && !this.inbuf.hasData()) { handler.endOfInput(this); } } if (this.contentDecoder != null && (this.session.getEventMask() & SelectionKey.OP_READ) > 0) { handler.inputReady(this, this.contentDecoder); if (this.contentDecoder.isCompleted()) { // Request entity received // Ready to receive a new request resetInput(); } } } catch (final HttpException ex) { resetInput(); handler.exception(this, ex); } catch (final Exception ex) { handler.exception(this, ex); } finally { // Finally set buffered input flag this.hasBufferedInput = this.inbuf.hasData(); } } public void produceOutput(final NHttpServerEventHandler handler) { try { if (this.status == ACTIVE) { if (this.contentEncoder == null && !this.outbuf.hasData()) { handler.responseReady(this); } if (this.contentEncoder != null) { handler.outputReady(this, this.contentEncoder); if (this.contentEncoder.isCompleted()) { resetOutput(); } } } if (this.outbuf.hasData()) { final int bytesWritten = this.outbuf.flush(this.session.channel()); if (bytesWritten > 0) { this.outTransportMetrics.incrementBytesTransferred(bytesWritten); } } if (!this.outbuf.hasData()) { if (this.status == CLOSING) { this.session.close(); this.status = CLOSED; resetOutput(); } } } catch (final Exception ex) { handler.exception(this, ex); } finally { // Finally set the buffered output flag this.hasBufferedOutput = this.outbuf.hasData(); } } @Override public void submitResponse(final HttpResponse response) throws IOException, HttpException { Args.notNull(response, "HTTP response"); assertNotClosed(); if (this.response != null) { throw new HttpException("Response already submitted"); } onResponseSubmitted(response); this.responseWriter.write(response); this.hasBufferedOutput = this.outbuf.hasData(); if (response.getStatusLine().getStatusCode() >= 200) { this.connMetrics.incrementResponseCount(); if (response.getEntity() != null) { this.response = response; prepareEncoder(response); } } this.session.setEvent(EventMask.WRITE); } @Override public boolean isResponseSubmitted() { return this.response != null; } @Override public void consumeInput(final NHttpServiceHandler handler) { consumeInput(new NHttpServerEventHandlerAdaptor(handler)); } @Override public void produceOutput(final NHttpServiceHandler handler) { produceOutput(new NHttpServerEventHandlerAdaptor(handler)); } } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpClientConnectionFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpClientConn0100644 0000000 0000000 00000016174 12613456025 032330 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.annotation.Immutable; import org.apache.http.config.ConnectionConfig; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.ConnSupport; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.codecs.DefaultHttpResponseParserFactory; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParamConfig; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default factory for plain (non-encrypted), non-blocking * {@link org.apache.http.nio.NHttpClientConnection}s. * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable public class DefaultNHttpClientConnectionFactory implements NHttpConnectionFactory { public static final DefaultNHttpClientConnectionFactory INSTANCE = new DefaultNHttpClientConnectionFactory(); private final ContentLengthStrategy incomingContentStrategy; private final ContentLengthStrategy outgoingContentStrategy; private final NHttpMessageParserFactory responseParserFactory; private final NHttpMessageWriterFactory requestWriterFactory; private final ByteBufferAllocator allocator; private final ConnectionConfig cconfig; /** * @deprecated (4.3) use {@link * DefaultNHttpClientConnectionFactory#DefaultNHttpClientConnectionFactory( * NHttpMessageParserFactory, NHttpMessageWriterFactory, ByteBufferAllocator, * ConnectionConfig)} */ @Deprecated public DefaultNHttpClientConnectionFactory( final HttpResponseFactory responseFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(); Args.notNull(responseFactory, "HTTP response factory"); Args.notNull(allocator, "Byte buffer allocator"); Args.notNull(params, "HTTP parameters"); this.allocator = allocator; this.incomingContentStrategy = null; this.outgoingContentStrategy = null; this.responseParserFactory = new DefaultHttpResponseParserFactory(null, responseFactory); this.requestWriterFactory = null; this.cconfig = HttpParamConfig.getConnectionConfig(params); } /** * @deprecated (4.3) use {@link * DefaultNHttpClientConnectionFactory#DefaultNHttpClientConnectionFactory( * ConnectionConfig)} */ @Deprecated public DefaultNHttpClientConnectionFactory(final HttpParams params) { this(DefaultHttpResponseFactory.INSTANCE, HeapByteBufferAllocator.INSTANCE, params); } /** * @since 4.3 */ public DefaultNHttpClientConnectionFactory( final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final NHttpMessageParserFactory responseParserFactory, final NHttpMessageWriterFactory requestWriterFactory, final ByteBufferAllocator allocator, final ConnectionConfig cconfig) { super(); this.incomingContentStrategy = incomingContentStrategy; this.outgoingContentStrategy = outgoingContentStrategy; this.responseParserFactory = responseParserFactory; this.requestWriterFactory = requestWriterFactory; this.allocator = allocator; this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; } /** * @since 4.3 */ public DefaultNHttpClientConnectionFactory( final NHttpMessageParserFactory responseParserFactory, final NHttpMessageWriterFactory requestWriterFactory, final ByteBufferAllocator allocator, final ConnectionConfig cconfig) { this(null, null, responseParserFactory, requestWriterFactory, allocator, cconfig); } /** * @since 4.3 */ public DefaultNHttpClientConnectionFactory( final NHttpMessageParserFactory responseParserFactory, final NHttpMessageWriterFactory requestWriterFactory, final ConnectionConfig cconfig) { this(null, null, responseParserFactory, requestWriterFactory, null, cconfig); } /** * @since 4.3 */ public DefaultNHttpClientConnectionFactory(final ConnectionConfig cconfig) { this(null, null, null, null, null, cconfig); } /** * @since 4.3 */ public DefaultNHttpClientConnectionFactory() { this(null, null, null, null, null, null); } /** * @deprecated (4.3) no longer used. */ @Deprecated protected DefaultNHttpClientConnection createConnection( final IOSession session, final HttpResponseFactory responseFactory, final ByteBufferAllocator allocator, final HttpParams params) { return new DefaultNHttpClientConnection(session, responseFactory, allocator, params); } @Override public DefaultNHttpClientConnection createConnection(final IOSession session) { return new DefaultNHttpClientConnection( session, this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), this.allocator, ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), this.incomingContentStrategy, this.outgoingContentStrategy, this.requestWriterFactory, this.responseParserFactory); } } ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpClientConnection.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpClientConn0100644 0000000 0000000 00000033733 12613456025 032330 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import java.nio.channels.SelectionKey; 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.HttpResponseFactory; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.nio.codecs.DefaultHttpRequestWriter; import org.apache.http.impl.nio.codecs.DefaultHttpRequestWriterFactory; import org.apache.http.impl.nio.codecs.DefaultHttpResponseParser; import org.apache.http.impl.nio.codecs.DefaultHttpResponseParserFactory; import org.apache.http.nio.NHttpClientEventHandler; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpClientIOTarget; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.reactor.EventMask; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.params.HttpParamConfig; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default implementation of the {@link org.apache.http.nio.NHttpClientConnection} * interface. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public class DefaultNHttpClientConnection extends NHttpConnectionBase implements NHttpClientIOTarget { protected final NHttpMessageParser responseParser; protected final NHttpMessageWriter requestWriter; /** * Creates a new instance of this class given the underlying I/O session. * * @param session the underlying I/O session. * @param responseFactory HTTP response factory. * @param allocator byte buffer allocator. * @param params HTTP parameters. * * @deprecated (4.3) use {@link DefaultNHttpClientConnection#DefaultNHttpClientConnection( * IOSession, int, int, ByteBufferAllocator, CharsetDecoder, CharsetEncoder, * MessageConstraints, ContentLengthStrategy, ContentLengthStrategy, * NHttpMessageWriterFactory, NHttpMessageParserFactory)} */ @Deprecated public DefaultNHttpClientConnection( final IOSession session, final HttpResponseFactory responseFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(session, allocator, params); Args.notNull(responseFactory, "Response factory"); this.responseParser = createResponseParser(this.inbuf, responseFactory, params); this.requestWriter = createRequestWriter(this.outbuf, params); this.hasBufferedInput = false; this.hasBufferedOutput = false; this.session.setBufferStatus(this); } /** * Creates new instance DefaultNHttpClientConnection given the underlying I/O session. * * @param session the underlying I/O session. * @param buffersize buffer size. Must be a positive number. * @param fragmentSizeHint fragment size hint. * @param allocator memory allocator. * If {@code null} {@link org.apache.http.nio.util.HeapByteBufferAllocator#INSTANCE} * will be used. * @param chardecoder decoder to be used for decoding HTTP protocol elements. * If {@code null} simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If {@code null} * {@link org.apache.http.impl.entity.LaxContentLengthStrategy#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If {@code null} * {@link org.apache.http.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used. * * @since 4.3 */ public DefaultNHttpClientConnection( final IOSession session, final int buffersize, final int fragmentSizeHint, final ByteBufferAllocator allocator, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final NHttpMessageWriterFactory requestWriterFactory, final NHttpMessageParserFactory responseParserFactory) { super(session, buffersize, fragmentSizeHint, allocator, chardecoder, charencoder, constraints, incomingContentStrategy, outgoingContentStrategy); this.requestWriter = (requestWriterFactory != null ? requestWriterFactory : DefaultHttpRequestWriterFactory.INSTANCE).create(this.outbuf); this.responseParser = (responseParserFactory != null ? responseParserFactory : DefaultHttpResponseParserFactory.INSTANCE).create(this.inbuf, constraints); } /** * @since 4.3 */ public DefaultNHttpClientConnection( final IOSession session, final int buffersize, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints) { this(session, buffersize, buffersize, null, chardecoder, charencoder, constraints, null, null, null, null); } /** * @since 4.3 */ public DefaultNHttpClientConnection(final IOSession session, final int buffersize) { this(session, buffersize, buffersize, null, null, null, null, null, null, null, null); } /** * Creates an instance of {@link NHttpMessageParser} to be used * by this connection for parsing incoming {@link HttpResponse} messages. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpMessageParser} interface. * * @return HTTP response parser. * * @deprecated (4.3) use constructor. */ @Deprecated protected NHttpMessageParser createResponseParser( final SessionInputBuffer buffer, final HttpResponseFactory responseFactory, final HttpParams params) { // override in derived class to specify a line parser final MessageConstraints constraints = HttpParamConfig.getMessageConstraints(params); return new DefaultHttpResponseParser(buffer, null, responseFactory, constraints); } /** * Creates an instance of {@link NHttpMessageWriter} to be used * by this connection for writing out outgoing {@link HttpRequest} messages. *

* This method can be overridden by a super class in order to provide * a different implementation of the {@link NHttpMessageWriter} interface. * * @return HTTP response parser. * * @deprecated (4.3) use constructor. */ @Deprecated protected NHttpMessageWriter createRequestWriter( final SessionOutputBuffer buffer, final HttpParams params) { // override in derived class to specify a line formatter return new DefaultHttpRequestWriter(buffer, null); } /** * @since 4.2 */ protected void onResponseReceived(final HttpResponse response) { } /** * @since 4.2 */ protected void onRequestSubmitted(final HttpRequest request) { } @Override public void resetInput() { this.response = null; this.contentDecoder = null; this.responseParser.reset(); } @Override public void resetOutput() { this.request = null; this.contentEncoder = null; this.requestWriter.reset(); } public void consumeInput(final NHttpClientEventHandler handler) { if (this.status != ACTIVE) { this.session.clearEvent(EventMask.READ); return; } try { if (this.response == null) { int bytesRead; do { bytesRead = this.responseParser.fillBuffer(this.session.channel()); if (bytesRead > 0) { this.inTransportMetrics.incrementBytesTransferred(bytesRead); } this.response = this.responseParser.parse(); } while (bytesRead > 0 && this.response == null); if (this.response != null) { if (this.response.getStatusLine().getStatusCode() >= 200) { final HttpEntity entity = prepareDecoder(this.response); this.response.setEntity(entity); this.connMetrics.incrementResponseCount(); } this.hasBufferedInput = this.inbuf.hasData(); onResponseReceived(this.response); handler.responseReceived(this); if (this.contentDecoder == null) { resetInput(); } } if (bytesRead == -1 && !this.inbuf.hasData()) { handler.endOfInput(this); } } if (this.contentDecoder != null && (this.session.getEventMask() & SelectionKey.OP_READ) > 0) { handler.inputReady(this, this.contentDecoder); if (this.contentDecoder.isCompleted()) { // Response entity received // Ready to receive a new response resetInput(); } } } catch (final HttpException ex) { resetInput(); handler.exception(this, ex); } catch (final Exception ex) { handler.exception(this, ex); } finally { // Finally set buffered input flag this.hasBufferedInput = this.inbuf.hasData(); } } public void produceOutput(final NHttpClientEventHandler handler) { try { if (this.status == ACTIVE) { if (this.contentEncoder == null && !this.outbuf.hasData()) { handler.requestReady(this); } if (this.contentEncoder != null) { handler.outputReady(this, this.contentEncoder); if (this.contentEncoder.isCompleted()) { resetOutput(); } } } if (this.outbuf.hasData()) { final int bytesWritten = this.outbuf.flush(this.session.channel()); if (bytesWritten > 0) { this.outTransportMetrics.incrementBytesTransferred(bytesWritten); } } if (!this.outbuf.hasData()) { if (this.status == CLOSING) { this.session.close(); this.status = CLOSED; resetOutput(); } } } catch (final Exception ex) { handler.exception(this, ex); } finally { // Finally set the buffered output flag this.hasBufferedOutput = this.outbuf.hasData(); } } @Override public void submitRequest(final HttpRequest request) throws IOException, HttpException { Args.notNull(request, "HTTP request"); assertNotClosed(); if (this.request != null) { throw new HttpException("Request already submitted"); } onRequestSubmitted(request); this.requestWriter.write(request); this.hasBufferedOutput = this.outbuf.hasData(); if (request instanceof HttpEntityEnclosingRequest && ((HttpEntityEnclosingRequest) request).getEntity() != null) { prepareEncoder(request); this.request = request; } this.connMetrics.incrementRequestCount(); this.session.setEvent(EventMask.WRITE); } @Override public boolean isRequestSubmitted() { return this.request != null; } @Override public void consumeInput(final NHttpClientHandler handler) { consumeInput(new NHttpClientEventHandlerAdaptor(handler)); } @Override public void produceOutput(final NHttpClientHandler handler) { produceOutput(new NHttpClientEventHandlerAdaptor(handler)); } } ././@LongLink0100644 0000000 0000000 00000000157 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultHttpClientIODispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultHttpClientIODis0100644 0000000 0000000 00000014424 12613456025 032260 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import javax.net.ssl.SSLContext; import org.apache.http.annotation.Immutable; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.nio.reactor.AbstractIODispatch; import org.apache.http.nio.NHttpClientEventHandler; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default {@link org.apache.http.nio.reactor.IOEventDispatch} implementation * that supports both plain (non-encrypted) and SSL encrypted client side HTTP * connections. * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable // provided injected dependencies are immutable public class DefaultHttpClientIODispatch extends AbstractIODispatch { private final NHttpClientEventHandler handler; private final NHttpConnectionFactory connFactory; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler. * * @param handler the client protocol handler. * @param connFactory HTTP client connection factory. */ public DefaultHttpClientIODispatch( final NHttpClientEventHandler handler, final NHttpConnectionFactory connFactory) { super(); this.handler = Args.notNull(handler, "HTTP client handler"); this.connFactory = Args.notNull(connFactory, "HTTP client connection factory"); } /** * @deprecated (4.3) use {@link DefaultHttpClientIODispatch#DefaultHttpClientIODispatch( * NHttpClientEventHandler, ConnectionConfig)} */ @Deprecated public DefaultHttpClientIODispatch( final NHttpClientEventHandler handler, final HttpParams params) { this(handler, new DefaultNHttpClientConnectionFactory(params)); } /** * @deprecated (4.3) use {@link DefaultHttpClientIODispatch#DefaultHttpClientIODispatch( * NHttpClientEventHandler, SSLContext, SSLSetupHandler, ConnectionConfig)} */ @Deprecated public DefaultHttpClientIODispatch( final NHttpClientEventHandler handler, final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { this(handler, new SSLNHttpClientConnectionFactory(sslcontext, sslHandler, params)); } /** * @deprecated (4.3) use {@link DefaultHttpClientIODispatch#DefaultHttpClientIODispatch( * NHttpClientEventHandler, SSLContext, ConnectionConfig)} */ @Deprecated public DefaultHttpClientIODispatch( final NHttpClientEventHandler handler, final SSLContext sslcontext, final HttpParams params) { this(handler, sslcontext, null, params); } /** * @since 4.3 */ public DefaultHttpClientIODispatch(final NHttpClientEventHandler handler, final ConnectionConfig config) { this(handler, new DefaultNHttpClientConnectionFactory(config)); } /** * @since 4.3 */ public DefaultHttpClientIODispatch( final NHttpClientEventHandler handler, final SSLContext sslcontext, final SSLSetupHandler sslHandler, final ConnectionConfig config) { this(handler, new SSLNHttpClientConnectionFactory(sslcontext, sslHandler, config)); } /** * @since 4.3 */ public DefaultHttpClientIODispatch( final NHttpClientEventHandler handler, final SSLContext sslcontext, final ConnectionConfig config) { this(handler, new SSLNHttpClientConnectionFactory(sslcontext, null, config)); } @Override protected DefaultNHttpClientConnection createConnection(final IOSession session) { return this.connFactory.createConnection(session); } @Override protected void onConnected(final DefaultNHttpClientConnection conn) { final Object attachment = conn.getContext().getAttribute(IOSession.ATTACHMENT_KEY); try { this.handler.connected(conn, attachment); } catch (final Exception ex) { this.handler.exception(conn, ex); } } @Override protected void onClosed(final DefaultNHttpClientConnection conn) { this.handler.closed(conn); } @Override protected void onException(final DefaultNHttpClientConnection conn, final IOException ex) { this.handler.exception(conn, ex); } @Override protected void onInputReady(final DefaultNHttpClientConnection conn) { conn.consumeInput(this.handler); } @Override protected void onOutputReady(final DefaultNHttpClientConnection conn) { conn.produceOutput(this.handler); } @Override protected void onTimeout(final DefaultNHttpClientConnection conn) { try { this.handler.timeout(conn); } catch (final Exception ex) { this.handler.exception(conn, ex); } } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/SSLContextUtils.java0100644 0000000 0000000 00000003571 12613456025 031755 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import javax.net.ssl.SSLContext; import java.security.NoSuchAlgorithmException; // TODO: to be replaced by SSLContext#getDefault() after upgrade to 1.6 class SSLContextUtils { static SSLContext getDefault() { SSLContext sslcontext; try { try { sslcontext = SSLContext.getInstance("Default"); } catch (NoSuchAlgorithmException ex) { sslcontext = SSLContext.getInstance("TLS"); } sslcontext.init(null, null, null); } catch (final Exception ex) { throw new IllegalStateException("Failure initializing default SSL context", ex); } return sslcontext; } } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpServerConnectionFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpServerConn0100644 0000000 0000000 00000015140 12613456025 032350 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; 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.impl.ConnSupport; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.impl.nio.codecs.DefaultHttpRequestParserFactory; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParamConfig; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default factory for plain (non-encrypted), non-blocking * {@link org.apache.http.nio.NHttpServerConnection}s. * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable public class DefaultNHttpServerConnectionFactory implements NHttpConnectionFactory { private final ContentLengthStrategy incomingContentStrategy; private final ContentLengthStrategy outgoingContentStrategy; private final NHttpMessageParserFactory requestParserFactory; private final NHttpMessageWriterFactory responseWriterFactory; private final ByteBufferAllocator allocator; private final ConnectionConfig cconfig; /** * @deprecated (4.3) use {@link * DefaultNHttpServerConnectionFactory#DefaultNHttpServerConnectionFactory( * ByteBufferAllocator, NHttpMessageParserFactory, NHttpMessageWriterFactory, * ConnectionConfig)} */ @Deprecated public DefaultNHttpServerConnectionFactory( final HttpRequestFactory requestFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(); Args.notNull(requestFactory, "HTTP request factory"); Args.notNull(allocator, "Byte buffer allocator"); Args.notNull(params, "HTTP parameters"); this.incomingContentStrategy = null; this.outgoingContentStrategy = null; this.requestParserFactory = new DefaultHttpRequestParserFactory(null, requestFactory); this.responseWriterFactory = null; this.allocator = allocator; this.cconfig = HttpParamConfig.getConnectionConfig(params); } /** * @deprecated (4.3) use {@link * DefaultNHttpServerConnectionFactory#DefaultNHttpServerConnectionFactory(ConnectionConfig)} */ @Deprecated public DefaultNHttpServerConnectionFactory(final HttpParams params) { this(DefaultHttpRequestFactory.INSTANCE, HeapByteBufferAllocator.INSTANCE, params); } /** * @deprecated (4.3) no longer used. */ @Deprecated protected DefaultNHttpServerConnection createConnection( final IOSession session, final HttpRequestFactory requestFactory, final ByteBufferAllocator allocator, final HttpParams params) { return new DefaultNHttpServerConnection(session, requestFactory, allocator, params); } /** * @since 4.3 */ public DefaultNHttpServerConnectionFactory( final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final NHttpMessageParserFactory requestParserFactory, final NHttpMessageWriterFactory responseWriterFactory, final ByteBufferAllocator allocator, final ConnectionConfig cconfig) { super(); this.incomingContentStrategy = incomingContentStrategy; this.outgoingContentStrategy = outgoingContentStrategy; this.requestParserFactory = requestParserFactory; this.responseWriterFactory = responseWriterFactory; this.allocator = allocator; this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; } /** * @since 4.3 */ public DefaultNHttpServerConnectionFactory( final ByteBufferAllocator allocator, final NHttpMessageParserFactory requestParserFactory, final NHttpMessageWriterFactory responseWriterFactory, final ConnectionConfig cconfig) { this(null, null, requestParserFactory, responseWriterFactory, allocator, cconfig); } /** * @since 4.3 */ public DefaultNHttpServerConnectionFactory(final ConnectionConfig config) { this(null, null, null, null, null, config); } /** * @since 4.3 */ public DefaultNHttpServerConnectionFactory() { this(null, null, null, null, null, null); } @Override public DefaultNHttpServerConnection createConnection(final IOSession session) { return new DefaultNHttpServerConnection(session, this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), this.allocator, ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), this.incomingContentStrategy, this.outgoingContentStrategy, this.requestParserFactory, this.responseWriterFactory); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/0040755 0000000 0000000 00000000000 12613456025 030075 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000150 12613460517 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/HttpServer.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/HttpServer.j0100644 0000000 0000000 00000013362 12613456025 032360 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.bootstrap; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.apache.http.ExceptionLogger; import org.apache.http.impl.nio.DefaultHttpServerIODispatch; import org.apache.http.impl.nio.DefaultNHttpServerConnection; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.NHttpServerEventHandler; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.ListenerEndpoint; /** * @since 4.4 */ public class HttpServer { enum Status { READY, ACTIVE, STOPPING } private final int port; private final InetAddress ifAddress; private final IOReactorConfig ioReactorConfig; private final NHttpServerEventHandler serverEventHandler; private final NHttpConnectionFactory connectionFactory; private final ExceptionLogger exceptionLogger; private final ExecutorService listenerExecutorService; private final ThreadGroup dispatchThreads; private final AtomicReference status; private final DefaultListeningIOReactor ioReactor; private volatile ListenerEndpoint endpoint; HttpServer( final int port, final InetAddress ifAddress, final IOReactorConfig ioReactorConfig, final NHttpServerEventHandler serverEventHandler, final NHttpConnectionFactory connectionFactory, final ExceptionLogger exceptionLogger) { this.port = port; this.ifAddress = ifAddress; this.ioReactorConfig = ioReactorConfig; this.serverEventHandler = serverEventHandler; this.connectionFactory = connectionFactory; this.exceptionLogger = exceptionLogger; this.listenerExecutorService = Executors.newSingleThreadExecutor( new ThreadFactoryImpl("HTTP-listener-" + this.port)); this.dispatchThreads = new ThreadGroup("I/O-dispatchers"); try { this.ioReactor = new DefaultListeningIOReactor( this.ioReactorConfig, new ThreadFactoryImpl("I/O-dispatch", this.dispatchThreads)); } catch (IOReactorException ex) { throw new IllegalStateException(ex); } this.ioReactor.setExceptionHandler(new IOReactorExceptionHandler() { @Override public boolean handle(final IOException ex) { exceptionLogger.log(ex); return false; } @Override public boolean handle(final RuntimeException ex) { exceptionLogger.log(ex); return false; } }); this.status = new AtomicReference(Status.READY); } public ListenerEndpoint getEndpoint() { return this.endpoint; } public void start() throws IOException { if (this.status.compareAndSet(Status.READY, Status.ACTIVE)) { this.endpoint = this.ioReactor.listen(new InetSocketAddress(this.ifAddress, this.port > 0 ? this.port : 0)); final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch( this.serverEventHandler, this.connectionFactory); this.listenerExecutorService.execute(new Runnable() { @Override public void run() { try { ioReactor.execute(ioEventDispatch); } catch (Exception ex) { exceptionLogger.log(ex); } } }); } } public void awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException { this.listenerExecutorService.awaitTermination(timeout, timeUnit); } public void shutdown(final long gracePeriod, final TimeUnit timeUnit) { if (this.status.compareAndSet(Status.ACTIVE, Status.STOPPING)) { try { this.ioReactor.shutdown(timeUnit.toMillis(gracePeriod)); } catch (IOException ex) { this.exceptionLogger.log(ex); } this.listenerExecutorService.shutdown(); } } } ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/package-info.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/package-info0100644 0000000 0000000 00000002413 12613456025 032341 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ /** * Embedded non-blocking server and server bootstrap. */ package org.apache.http.impl.nio.bootstrap; ././@LongLink0100644 0000000 0000000 00000000155 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/ServerBootstrap.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/ServerBootst0100644 0000000 0000000 00000034266 12613456025 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.impl.nio.bootstrap; import java.net.InetAddress; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.ExceptionLogger; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpResponseInterceptor; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultNHttpServerConnection; import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory; import org.apache.http.impl.nio.SSLNHttpServerConnectionFactory; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.protocol.HttpAsyncExpectationVerifier; import org.apache.http.nio.protocol.HttpAsyncRequestHandler; import org.apache.http.nio.protocol.HttpAsyncRequestHandlerMapper; import org.apache.http.nio.protocol.HttpAsyncService; import org.apache.http.nio.protocol.UriHttpAsyncRequestHandlerMapper; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessorBuilder; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; /** * @since 4.4 */ public class ServerBootstrap { private int listenerPort; private InetAddress localAddress; private IOReactorConfig ioReactorConfig; private ConnectionConfig connectionConfig; private LinkedList requestFirst; private LinkedList requestLast; private LinkedList responseFirst; private LinkedList responseLast; private String serverInfo; private HttpProcessor httpProcessor; private ConnectionReuseStrategy connStrategy; private HttpResponseFactory responseFactory; private HttpAsyncRequestHandlerMapper handlerMapper; private Map> handlerMap; private HttpAsyncExpectationVerifier expectationVerifier; private SSLContext sslContext; private SSLSetupHandler sslSetupHandler; private NHttpConnectionFactory connectionFactory; private ExceptionLogger exceptionLogger; private ServerBootstrap() { } public static ServerBootstrap bootstrap() { return new ServerBootstrap(); } /** * Sets listener port number. */ public final ServerBootstrap setListenerPort(final int listenerPort) { this.listenerPort = listenerPort; return this; } /** * Assigns local interface for the listener. */ public final ServerBootstrap setLocalAddress(final InetAddress localAddress) { this.localAddress = localAddress; return this; } /** * Sets I/O reactor configuration. */ public final ServerBootstrap setIOReactorConfig(final IOReactorConfig ioReactorConfig) { this.ioReactorConfig = ioReactorConfig; return this; } /** * Sets connection configuration. *

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

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

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

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

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

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

* Please note this value can be overridden by the {@link #setHandlerMapper( * org.apache.http.nio.protocol.HttpAsyncRequestHandlerMapper)} )} method. * * @param pattern the pattern to register the handler for. * @param handler the handler. */ public final ServerBootstrap registerHandler(final String pattern, final HttpAsyncRequestHandler handler) { if (pattern == null || handler == null) { return this; } if (handlerMap == null) { handlerMap = new HashMap>(); } handlerMap.put(pattern, handler); return this; } /** * Assigns {@link org.apache.http.nio.protocol.HttpAsyncExpectationVerifier} instance. */ public final ServerBootstrap setExpectationVerifier(final HttpAsyncExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; return this; } /** * Assigns {@link org.apache.http.nio.NHttpConnectionFactory} instance. */ public final ServerBootstrap setConnectionFactory( final NHttpConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; return this; } /** * Assigns {@link javax.net.ssl.SSLContext} instance. *

* Please note this value can be overridden by the {@link #setConnectionFactory( * org.apache.http.nio.NHttpConnectionFactory)} method. */ public final ServerBootstrap setSslContext(final SSLContext sslContext) { this.sslContext = sslContext; return this; } /** * Assigns {@link org.apache.http.nio.reactor.ssl.SSLSetupHandler} instance. *

* Please note this value can be overridden by the {@link #setConnectionFactory( * org.apache.http.nio.NHttpConnectionFactory)} method. */ public ServerBootstrap setSslSetupHandler(final SSLSetupHandler sslSetupHandler) { this.sslSetupHandler = sslSetupHandler; return this; } /** * Assigns {@link org.apache.http.ExceptionLogger} instance. */ public final ServerBootstrap setExceptionLogger(final ExceptionLogger exceptionLogger) { this.exceptionLogger = exceptionLogger; return this; } public HttpServer create() { HttpProcessor httpProcessorCopy = this.httpProcessor; if (httpProcessorCopy == null) { final HttpProcessorBuilder b = HttpProcessorBuilder.create(); if (requestFirst != null) { for (final HttpRequestInterceptor i: requestFirst) { b.addFirst(i); } } if (responseFirst != null) { for (final HttpResponseInterceptor i: responseFirst) { b.addFirst(i); } } String serverInfoCopy = this.serverInfo; if (serverInfoCopy == null) { serverInfoCopy = "Apache-HttpCore-NIO/1.1"; } b.addAll( new ResponseDate(), new ResponseServer(serverInfoCopy), new ResponseContent(), new ResponseConnControl()); if (requestLast != null) { for (final HttpRequestInterceptor i: requestLast) { b.addLast(i); } } if (responseLast != null) { for (final HttpResponseInterceptor i: responseLast) { b.addLast(i); } } httpProcessorCopy = b.build(); } HttpAsyncRequestHandlerMapper handlerMapperCopy = this.handlerMapper; if (handlerMapperCopy == null) { final UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper(); if (handlerMap != null) { for (Map.Entry> entry: handlerMap.entrySet()) { reqistry.register(entry.getKey(), entry.getValue()); } } handlerMapperCopy = reqistry; } ConnectionReuseStrategy connStrategyCopy = this.connStrategy; if (connStrategyCopy == null) { connStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE; } HttpResponseFactory responseFactoryCopy = this.responseFactory; if (responseFactoryCopy == null) { responseFactoryCopy = DefaultHttpResponseFactory.INSTANCE; } NHttpConnectionFactory connectionFactoryCopy = this.connectionFactory; if (connectionFactoryCopy == null) { if (this.sslContext != null) { connectionFactoryCopy = new SSLNHttpServerConnectionFactory( this.sslContext, this.sslSetupHandler, this.connectionConfig); } else { connectionFactoryCopy = new DefaultNHttpServerConnectionFactory(this.connectionConfig); } } ExceptionLogger exceptionLoggerCopy = this.exceptionLogger; if (exceptionLoggerCopy == null) { exceptionLoggerCopy = ExceptionLogger.NO_OP; } final HttpAsyncService httpService = new HttpAsyncService( httpProcessorCopy, connStrategyCopy, responseFactoryCopy, handlerMapperCopy, this.expectationVerifier, exceptionLoggerCopy); return new HttpServer(this.listenerPort, this.localAddress, this.ioReactorConfig, httpService, connectionFactoryCopy, exceptionLoggerCopy); } } ././@LongLink0100644 0000000 0000000 00000000157 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/ThreadFactoryImpl.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/bootstrap/ThreadFactor0100644 0000000 0000000 00000003645 12613456025 032373 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.bootstrap; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; /** * @since 4.4 */ class ThreadFactoryImpl implements ThreadFactory { private final String namePrefix; private final ThreadGroup group; private final AtomicLong count; ThreadFactoryImpl(final String namePrefix, final ThreadGroup group) { this.namePrefix = namePrefix; this.group = group; this.count = new AtomicLong(); } ThreadFactoryImpl(final String namePrefix) { this(namePrefix, null); } @Override public Thread newThread(final Runnable target) { return new Thread(this.group, target, this.namePrefix + "-" + this.count.incrementAndGet()); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/0040755 0000000 0000000 00000000000 12613456025 027320 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/ChunkDecoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/ChunkDecoder.ja0100644 0000000 0000000 00000024761 12613456025 032201 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.List; import org.apache.http.ConnectionClosedException; import org.apache.http.Header; import org.apache.http.MalformedChunkCodingException; import org.apache.http.MessageConstraintException; import org.apache.http.ParseException; import org.apache.http.TruncatedChunkException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.message.BufferedHeader; import org.apache.http.nio.reactor.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 encoder can be of unlimited length. * * @since 4.0 */ @NotThreadSafe public class ChunkDecoder extends AbstractContentDecoder { private static final int READ_CONTENT = 0; private static final int READ_FOOTERS = 1; private static final int COMPLETED = 2; private int state; private boolean endOfChunk; private boolean endOfStream; private CharArrayBuffer lineBuf; private int chunkSize; private int pos; private final MessageConstraints constraints; private final List trailerBufs; private Header[] footers; /** * @since 4.4 */ public ChunkDecoder( final ReadableByteChannel channel, final SessionInputBuffer buffer, final MessageConstraints constraints, final HttpTransportMetricsImpl metrics) { super(channel, buffer, metrics); this.state = READ_CONTENT; this.chunkSize = -1; this.pos = 0; this.endOfChunk = false; this.endOfStream = false; this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; this.trailerBufs = new ArrayList(); } public ChunkDecoder( final ReadableByteChannel channel, final SessionInputBuffer buffer, final HttpTransportMetricsImpl metrics) { this(channel, buffer, null, metrics); } private void readChunkHead() throws IOException { if (this.lineBuf == null) { this.lineBuf = new CharArrayBuffer(32); } else { this.lineBuf.clear(); } if (this.endOfChunk) { if (this.buffer.readLine(this.lineBuf, this.endOfStream)) { if (!this.lineBuf.isEmpty()) { throw new MalformedChunkCodingException("CRLF expected at end of chunk"); } } else { if (this.buffer.length() > 2 || this.endOfStream) { throw new MalformedChunkCodingException("CRLF expected at end of chunk"); } return; } this.endOfChunk = false; } final boolean lineComplete = this.buffer.readLine(this.lineBuf, this.endOfStream); final int maxLineLen = this.constraints.getMaxLineLength(); if (maxLineLen > 0 && (this.lineBuf.length() > maxLineLen || (!lineComplete && this.buffer.length() > maxLineLen))) { throw new MessageConstraintException("Maximum line length limit exceeded"); } if (lineComplete) { int separator = this.lineBuf.indexOf(';'); if (separator < 0) { separator = this.lineBuf.length(); } try { final String s = this.lineBuf.substringTrimmed(0, separator); this.chunkSize = Integer.parseInt(s, 16); } catch (final NumberFormatException e) { throw new MalformedChunkCodingException("Bad chunk header"); } this.pos = 0; } else if (this.endOfStream) { throw new ConnectionClosedException("Premature end of chunk coded message body: " + "closing chunk expected"); } } private void parseHeader() throws IOException { final CharArrayBuffer current = this.lineBuf; final int count = this.trailerBufs.size(); if ((this.lineBuf.charAt(0) == ' ' || this.lineBuf.charAt(0) == '\t') && count > 0) { // Handle folded header line final CharArrayBuffer previous = this.trailerBufs.get(count - 1); int i = 0; while (i < current.length()) { final char ch = current.charAt(i); if (ch != ' ' && ch != '\t') { break; } i++; } final int maxLineLen = this.constraints.getMaxLineLength(); 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 { this.trailerBufs.add(current); this.lineBuf = null; } } private void processFooters() throws IOException { final int count = this.trailerBufs.size(); if (count > 0) { this.footers = new Header[this.trailerBufs.size()]; for (int i = 0; i < this.trailerBufs.size(); i++) { try { this.footers[i] = new BufferedHeader(this.trailerBufs.get(i)); } catch (final ParseException ex) { throw new IOException(ex.getMessage()); } } } this.trailerBufs.clear(); } @Override public int read(final ByteBuffer dst) throws IOException { Args.notNull(dst, "Byte buffer"); if (this.state == COMPLETED) { return -1; } int totalRead = 0; while (this.state != COMPLETED) { if (!this.buffer.hasData() || this.chunkSize == -1) { final int bytesRead = fillBufferFromChannel(); if (bytesRead == -1) { this.endOfStream = true; } } switch (this.state) { case READ_CONTENT: if (this.chunkSize == -1) { readChunkHead(); if (this.chunkSize == -1) { // Unable to read a chunk head return totalRead; } if (this.chunkSize == 0) { // Last chunk. Read footers this.chunkSize = -1; this.state = READ_FOOTERS; break; } } final int maxLen = this.chunkSize - this.pos; final int len = this.buffer.read(dst, maxLen); if (len > 0) { this.pos += len; totalRead += len; } else { if (!this.buffer.hasData() && this.endOfStream) { this.state = COMPLETED; this.completed = true; throw new TruncatedChunkException("Truncated chunk " + "( expected size: " + this.chunkSize + "; actual size: " + this.pos + ")"); } } if (this.pos == this.chunkSize) { // At the end of the chunk this.chunkSize = -1; this.pos = 0; this.endOfChunk = true; break; } return totalRead; case READ_FOOTERS: if (this.lineBuf == null) { this.lineBuf = new CharArrayBuffer(32); } else { this.lineBuf.clear(); } if (!this.buffer.readLine(this.lineBuf, this.endOfStream)) { // Unable to read a footer if (this.endOfStream) { this.state = COMPLETED; this.completed = true; } return totalRead; } if (this.lineBuf.length() > 0) { final int maxHeaderCount = this.constraints.getMaxHeaderCount(); if (maxHeaderCount > 0 && trailerBufs.size() >= maxHeaderCount) { throw new MessageConstraintException("Maximum header count exceeded"); } parseHeader(); } else { this.state = COMPLETED; this.completed = true; processFooters(); } break; } } return totalRead; } public Header[] getFooters() { if (this.footers != null) { return this.footers.clone(); } else { return new Header[] {}; } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("[chunk-coded; completed: "); sb.append(this.completed); sb.append("]"); return sb.toString(); } } ././@LongLink0100644 0000000 0000000 00000000173 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResponseParserFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResp0100644 0000000 0000000 00000005362 12613456025 032324 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; 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.message.BasicLineParser; import org.apache.http.message.LineParser; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.reactor.SessionInputBuffer; /** * Default factory for response message parsers. * * @since 4.3 */ @Immutable public class DefaultHttpResponseParserFactory implements NHttpMessageParserFactory { public static final DefaultHttpResponseParserFactory INSTANCE = new DefaultHttpResponseParserFactory(); private final LineParser lineParser; private final HttpResponseFactory responseFactory; public DefaultHttpResponseParserFactory(final LineParser lineParser, final HttpResponseFactory responseFactory) { super(); this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; this.responseFactory = responseFactory != null ? responseFactory : DefaultHttpResponseFactory.INSTANCE; } public DefaultHttpResponseParserFactory() { this(null, null); } @Override public NHttpMessageParser create(final SessionInputBuffer buffer, final MessageConstraints constraints) { return new DefaultHttpResponseParser(buffer, lineParser, responseFactory, constraints); } } ././@LongLink0100644 0000000 0000000 00000000164 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResponseWriter.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResp0100644 0000000 0000000 00000006014 12613456025 032317 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.message.LineFormatter; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.CharArrayBuffer; /** * Default {@link org.apache.http.nio.NHttpMessageWriter} implementation * for {@link HttpResponse}s. * * @since 4.1 */ @SuppressWarnings("deprecation") @NotThreadSafe public class DefaultHttpResponseWriter extends AbstractMessageWriter { /** * @deprecated (4.3) use * {@link DefaultHttpResponseWriter#DefaultHttpResponseWriter(SessionOutputBuffer, LineFormatter)} */ @Deprecated public DefaultHttpResponseWriter(final SessionOutputBuffer buffer, final LineFormatter formatter, final HttpParams params) { super(buffer, formatter, params); } /** * Creates an instance of DefaultHttpResponseWriter. * * @param buffer the session output buffer. * @param formatter the line formatter If {@code null} * {@link org.apache.http.message.BasicLineFormatter#INSTANCE} will be used. * * @since 4.3 */ public DefaultHttpResponseWriter( final SessionOutputBuffer buffer, final LineFormatter formatter) { super(buffer, formatter); } /** * @since 4.3 */ public DefaultHttpResponseWriter(final SessionOutputBuffer buffer) { super(buffer, null); } @Override protected void writeHeadLine(final HttpResponse message) throws IOException { final CharArrayBuffer buffer = lineFormatter.formatStatusLine( this.lineBuf, message.getStatusLine()); this.sessionBuffer.writeLine(buffer); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/ChunkEncoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/ChunkEncoder.ja0100644 0000000 0000000 00000012616 12613456025 032207 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.io.BufferInfo; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.util.CharArrayBuffer; /** * Implements chunked transfer coding. The content is sent in small chunks. * Entities transferred using this decoder can be of unlimited length. * * @since 4.0 */ @NotThreadSafe public class ChunkEncoder extends AbstractContentEncoder { private final int fragHint; private final CharArrayBuffer lineBuffer; private final BufferInfo bufferinfo; /** * @since 4.3 * * @param channel underlying channel. * @param buffer session buffer. * @param metrics transport metrics. * @param fragementSizeHint fragment size hint defining an minimal size of a fragment * that should be written out directly to the channel bypassing the session buffer. * Value {@code 0} disables fragment buffering. */ public ChunkEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics, final int fragementSizeHint) { super(channel, buffer, metrics); this.fragHint = fragementSizeHint > 0 ? fragementSizeHint : 0; this.lineBuffer = new CharArrayBuffer(16); if (buffer instanceof BufferInfo) { this.bufferinfo = (BufferInfo) buffer; } else { this.bufferinfo = null; } } public ChunkEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { this(channel, buffer, metrics, 0); } @Override public int write(final ByteBuffer src) throws IOException { if (src == null) { return 0; } assertNotCompleted(); int total = 0; while (src.hasRemaining()) { int chunk = src.remaining(); int avail; if (this.bufferinfo != null) { avail = this.bufferinfo.available(); } else { avail = 4096; } // subtract the length of the longest chunk header // 12345678\r\n // \r\n avail -= 12; if (avail > 0) { if (avail < chunk) { // write no more than 'avail' bytes chunk = avail; this.lineBuffer.clear(); this.lineBuffer.append(Integer.toHexString(chunk)); this.buffer.writeLine(this.lineBuffer); final int oldlimit = src.limit(); src.limit(src.position() + chunk); this.buffer.write(src); src.limit(oldlimit); } else { // write all this.lineBuffer.clear(); this.lineBuffer.append(Integer.toHexString(chunk)); this.buffer.writeLine(this.lineBuffer); this.buffer.write(src); } this.lineBuffer.clear(); this.buffer.writeLine(this.lineBuffer); total += chunk; } if (this.buffer.length() >= this.fragHint || src.hasRemaining()) { final int bytesWritten = flushToChannel(); if (bytesWritten == 0) { break; } } } return total; } @Override public void complete() throws IOException { assertNotCompleted(); this.lineBuffer.clear(); this.lineBuffer.append("0"); this.buffer.writeLine(this.lineBuffer); this.lineBuffer.clear(); this.buffer.writeLine(this.lineBuffer); super.complete(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("[chunk-coded; completed: "); sb.append(isCompleted()); sb.append("]"); return sb.toString(); } } ././@LongLink0100644 0000000 0000000 00000000172 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequestParserFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequ0100644 0000000 0000000 00000005335 12613456025 032327 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; 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.message.BasicLineParser; import org.apache.http.message.LineParser; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.reactor.SessionInputBuffer; /** * Default factory for request message parsers. * * @since 4.3 */ @Immutable public class DefaultHttpRequestParserFactory implements NHttpMessageParserFactory { public static final DefaultHttpRequestParserFactory INSTANCE = new DefaultHttpRequestParserFactory(); private final LineParser lineParser; private final HttpRequestFactory requestFactory; public DefaultHttpRequestParserFactory(final LineParser lineParser, final HttpRequestFactory requestFactory) { super(); this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; this.requestFactory = requestFactory != null ? requestFactory : DefaultHttpRequestFactory.INSTANCE; } public DefaultHttpRequestParserFactory() { this(null, null); } @Override public NHttpMessageParser create(final SessionInputBuffer buffer, final MessageConstraints constraints) { return new DefaultHttpRequestParser(buffer, lineParser, requestFactory, constraints); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/package-info.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/package-info.ja0100644 0000000 0000000 00000002473 12613456025 032163 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 asynchronous, even driven communication. */ package org.apache.http.impl.nio.codecs; ././@LongLink0100644 0000000 0000000 00000000163 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequestParser.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequ0100644 0000000 0000000 00000010651 12613456025 032324 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; 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.message.LineParser; import org.apache.http.message.ParserCursor; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; /** * Default {@link org.apache.http.nio.NHttpMessageParser} implementation * for {@link HttpRequest}s. * * @since 4.1 */ @SuppressWarnings("deprecation") @NotThreadSafe public class DefaultHttpRequestParser extends AbstractMessageParser { private final HttpRequestFactory requestFactory; /** * Creates an instance of this class. * * @param buffer the session input buffer. * @param parser the line parser. * @param params HTTP parameters. * * @deprecated (4.3) use * {@link DefaultHttpRequestParser#DefaultHttpRequestParser( * SessionInputBuffer, LineParser, HttpRequestFactory, MessageConstraints)} */ @Deprecated public DefaultHttpRequestParser( final SessionInputBuffer buffer, final LineParser parser, final HttpRequestFactory requestFactory, final HttpParams params) { super(buffer, parser, params); Args.notNull(requestFactory, "Request factory"); this.requestFactory = requestFactory; } /** * Creates an instance of DefaultHttpRequestParser. * * @param buffer the session input buffer. * @param parser the line parser. If {@code null} * {@link org.apache.http.message.BasicLineParser#INSTANCE} will be used. * @param requestFactory the request factory. If {@code null} * {@link DefaultHttpRequestFactory#INSTANCE} will be used. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * * @since 4.3 */ public DefaultHttpRequestParser( final SessionInputBuffer buffer, final LineParser parser, final HttpRequestFactory requestFactory, final MessageConstraints constraints) { super(buffer, parser, constraints); this.requestFactory = requestFactory != null ? requestFactory : DefaultHttpRequestFactory.INSTANCE; } /** * @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); } @Override protected HttpRequest createMessage(final CharArrayBuffer buffer) throws HttpException, ParseException { final ParserCursor cursor = new ParserCursor(0, buffer.length()); final RequestLine requestLine = lineParser.parseRequestLine(buffer, cursor); return this.requestFactory.newHttpRequest(requestLine); } } ././@LongLink0100644 0000000 0000000 00000000164 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResponseParser.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResp0100644 0000000 0000000 00000010451 12613456025 032317 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; 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.message.LineParser; import org.apache.http.message.ParserCursor; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; /** * Default {@link org.apache.http.nio.NHttpMessageParser} implementation * for {@link HttpResponse}s. * * @since 4.1 */ @SuppressWarnings("deprecation") @NotThreadSafe public class DefaultHttpResponseParser extends AbstractMessageParser { private final HttpResponseFactory responseFactory; /** * @deprecated (4.3) use * {@link DefaultHttpResponseParser#DefaultHttpResponseParser( * SessionInputBuffer, LineParser, HttpResponseFactory, MessageConstraints)} */ @Deprecated public DefaultHttpResponseParser( final SessionInputBuffer buffer, final LineParser parser, final HttpResponseFactory responseFactory, final HttpParams params) { super(buffer, parser, params); Args.notNull(responseFactory, "Response factory"); this.responseFactory = responseFactory; } /** * Creates an instance of DefaultHttpResponseParser. * * @param buffer the session input buffer. * @param parser the line parser. If {@code null} * {@link org.apache.http.message.BasicLineParser#INSTANCE} will be used. * @param responseFactory the response factory. If {@code null} * {@link DefaultHttpResponseFactory#INSTANCE} will be used. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * * @since 4.3 */ public DefaultHttpResponseParser( final SessionInputBuffer buffer, final LineParser parser, final HttpResponseFactory responseFactory, final MessageConstraints constraints) { super(buffer, parser, constraints); this.responseFactory = responseFactory != null ? responseFactory : DefaultHttpResponseFactory.INSTANCE; } /** * @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); } @Override protected HttpResponse createMessage(final CharArrayBuffer buffer) throws HttpException, ParseException { final ParserCursor cursor = new ParserCursor(0, buffer.length()); final StatusLine statusline = lineParser.parseStatusLine(buffer, cursor); return this.responseFactory.newHttpResponse(statusline, null); } } ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractMessageWriter.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractMessage0100644 0000000 0000000 00000010407 12613456025 032312 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.util.Iterator; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.message.BasicLineFormatter; import org.apache.http.message.LineFormatter; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; /** * Abstract {@link NHttpMessageWriter} that serves as a base for all message * writer implementations. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public abstract class AbstractMessageWriter implements NHttpMessageWriter { protected final SessionOutputBuffer sessionBuffer; protected final CharArrayBuffer lineBuf; protected final LineFormatter lineFormatter; /** * Creates an instance of this class. * * @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(64); this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatter.INSTANCE; } /** * Creates an instance of AbstractMessageWriter. * * @param buffer the session output buffer. * @param formatter the line formatter If {@code null} {@link BasicLineFormatter#INSTANCE} * will be used. * * @since 4.3 */ public AbstractMessageWriter( final SessionOutputBuffer buffer, final LineFormatter formatter) { super(); this.sessionBuffer = Args.notNull(buffer, "Session input buffer"); this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatter.INSTANCE; this.lineBuf = new CharArrayBuffer(64); } @Override public void reset() { } /** * Writes out the first line of {@link HttpMessage}. * * @param message HTTP message. */ protected abstract void writeHeadLine(T message) throws IOException; @Override public void write(final T message) throws IOException, HttpException { Args.notNull(message, "HTTP message"); writeHeadLine(message); for (final Iterator it = message.headerIterator(); it.hasNext(); ) { final Header header = (Header) it.next(); this.sessionBuffer.writeLine (lineFormatter.formatHeader(this.lineBuf, header)); } this.lineBuf.clear(); this.sessionBuffer.writeLine(this.lineBuf); } } ././@LongLink0100644 0000000 0000000 00000000173 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResponseWriterFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResp0100644 0000000 0000000 00000004473 12613456025 032326 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import org.apache.http.HttpResponse; import org.apache.http.annotation.Immutable; import org.apache.http.message.BasicLineFormatter; import org.apache.http.message.LineFormatter; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.reactor.SessionOutputBuffer; /** * Default factory for response message writers. * * @since 4.3 */ @Immutable public class DefaultHttpResponseWriterFactory implements NHttpMessageWriterFactory { public static final DefaultHttpResponseWriterFactory INSTANCE = new DefaultHttpResponseWriterFactory(); private final LineFormatter lineFormatter; public DefaultHttpResponseWriterFactory(final LineFormatter lineFormatter) { super(); this.lineFormatter = lineFormatter != null ? lineFormatter : BasicLineFormatter.INSTANCE; } public DefaultHttpResponseWriterFactory() { this(null); } @Override public NHttpMessageWriter create(final SessionOutputBuffer buffer) { return new DefaultHttpResponseWriter(buffer, lineFormatter); } } ././@LongLink0100644 0000000 0000000 00000000172 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequestWriterFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequ0100644 0000000 0000000 00000004461 12613456025 032326 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import org.apache.http.HttpRequest; import org.apache.http.annotation.Immutable; import org.apache.http.message.BasicLineFormatter; import org.apache.http.message.LineFormatter; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.reactor.SessionOutputBuffer; /** * Default factory for request message writers. * * @since 4.3 */ @Immutable public class DefaultHttpRequestWriterFactory implements NHttpMessageWriterFactory { public static final DefaultHttpRequestWriterFactory INSTANCE = new DefaultHttpRequestWriterFactory(); private final LineFormatter lineFormatter; public DefaultHttpRequestWriterFactory(final LineFormatter lineFormatter) { super(); this.lineFormatter = lineFormatter != null ? lineFormatter : BasicLineFormatter.INSTANCE; } public DefaultHttpRequestWriterFactory() { this(null); } @Override public NHttpMessageWriter create(final SessionOutputBuffer buffer) { return new DefaultHttpRequestWriter(buffer, lineFormatter); } } ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimitedEncoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimited0100644 0000000 0000000 00000015003 12613456025 032301 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.nio.FileContentEncoder; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.util.Args; /** * Content encoder that cuts off after a defined number of bytes. This class * is used to send content of HTTP messages where the end of the content entity * is determined by the value of the {@code Content-Length header}. * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE} * long. *

* This decoder is optimized to transfer data directly from * a {@link FileChannel} to the underlying I/O session's channel whenever * possible avoiding intermediate buffering in the session buffer. * * @since 4.0 */ @NotThreadSafe public class LengthDelimitedEncoder extends AbstractContentEncoder implements FileContentEncoder { private final long contentLength; private final int fragHint; private long remaining; /** * @since 4.3 * * @param channel underlying channel. * @param buffer session buffer. * @param metrics transport metrics. * @param contentLength content length. * @param fragementSizeHint fragment size hint defining an minimal size of a fragment * that should be written out directly to the channel bypassing the session buffer. * Value {@code 0} disables fragment buffering. */ public LengthDelimitedEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics, final long contentLength, final int fragementSizeHint) { super(channel, buffer, metrics); Args.notNegative(contentLength, "Content length"); this.contentLength = contentLength; this.fragHint = fragementSizeHint > 0 ? fragementSizeHint : 0; this.remaining = contentLength; } public LengthDelimitedEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics, final long contentLength) { this(channel, buffer, metrics, contentLength, 0); } private int nextChunk(final ByteBuffer src) { return (int) Math.min(Math.min(this.remaining, Integer.MAX_VALUE), src.remaining()); } @Override public int write(final ByteBuffer src) throws IOException { if (src == null) { return 0; } assertNotCompleted(); int total = 0; while (src.hasRemaining() && this.remaining > 0) { if (this.buffer.hasData() || this.fragHint > 0) { final int chunk = nextChunk(src); if (chunk <= this.fragHint) { final int capacity = this.fragHint - this.buffer.length(); if (capacity > 0) { final int limit = Math.min(capacity, chunk); final int bytesWritten = writeToBuffer(src, limit); this.remaining -= bytesWritten; total += bytesWritten; } } } if (this.buffer.hasData()) { final int chunk = nextChunk(src); if (this.buffer.length() >= this.fragHint || chunk > 0) { final int bytesWritten = flushToChannel(); if (bytesWritten == 0) { break; } } } if (!this.buffer.hasData()) { final int chunk = nextChunk(src); if (chunk > this.fragHint) { final int bytesWritten = writeToChannel(src, chunk); this.remaining -= bytesWritten; total += bytesWritten; if (bytesWritten == 0) { break; } } } } if (this.remaining <= 0) { super.complete(); } return total; } @Override public long transfer( final FileChannel src, final long position, final long count) throws IOException { if (src == null) { return 0; } assertNotCompleted(); flushToChannel(); if (this.buffer.hasData()) { return 0; } final long chunk = Math.min(this.remaining, count); final long bytesWritten = src.transferTo(position, chunk, this.channel); if (bytesWritten > 0) { this.metrics.incrementBytesTransferred(bytesWritten); } this.remaining -= bytesWritten; if (this.remaining <= 0) { super.complete(); } return bytesWritten; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("[content length: "); sb.append(this.contentLength); sb.append("; pos: "); sb.append(this.contentLength - this.remaining); sb.append("; completed: "); sb.append(isCompleted()); sb.append("]"); return sb.toString(); } } ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractMessageParser.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractMessage0100644 0000000 0000000 00000021633 12613456025 032315 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.List; 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.message.BasicLineParser; import org.apache.http.message.LineParser; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.reactor.SessionInputBuffer; 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 {@link NHttpMessageParser} that serves as a base for all message * parser implementations. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public abstract class AbstractMessageParser implements NHttpMessageParser { private final SessionInputBuffer sessionBuffer; private static final int READ_HEAD_LINE = 0; private static final int READ_HEADERS = 1; private static final int COMPLETED = 2; private int state; private boolean endOfStream; private T message; private CharArrayBuffer lineBuf; private final List headerBufs; protected final LineParser lineParser; private final MessageConstraints constraints; /** * Creates an instance of this class. * * @param buffer the session input buffer. * @param lineParser 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 lineParser, final HttpParams params) { super(); Args.notNull(buffer, "Session input buffer"); Args.notNull(params, "HTTP parameters"); this.sessionBuffer = buffer; this.state = READ_HEAD_LINE; this.endOfStream = false; this.headerBufs = new ArrayList(); this.constraints = HttpParamConfig.getMessageConstraints(params); this.lineParser = (lineParser != null) ? lineParser : BasicLineParser.INSTANCE; } /** * Creates an instance of AbstractMessageParser. * * @param buffer the session input buffer. * @param lineParser the line parser. If {@code null} {@link BasicLineParser#INSTANCE} * will be used. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * * @since 4.3 */ public AbstractMessageParser( final SessionInputBuffer buffer, final LineParser lineParser, final MessageConstraints constraints) { super(); this.sessionBuffer = Args.notNull(buffer, "Session input buffer"); this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; this.headerBufs = new ArrayList(); this.state = READ_HEAD_LINE; this.endOfStream = false; } @Override public void reset() { this.state = READ_HEAD_LINE; this.endOfStream = false; this.headerBufs.clear(); this.message = null; } @Override public int fillBuffer(final ReadableByteChannel channel) throws IOException { final int bytesRead = this.sessionBuffer.fill(channel); if (bytesRead == -1) { this.endOfStream = true; } return bytesRead; } /** * Creates {@link HttpMessage} instance based on the content of the input * buffer containing the first line of the incoming HTTP message. * * @param buffer the line buffer. * @return HTTP message. * @throws HttpException in case of HTTP protocol violation * @throws ParseException in case of a parse error. */ protected abstract T createMessage(CharArrayBuffer buffer) throws HttpException, ParseException; private void parseHeadLine() throws HttpException, ParseException { this.message = createMessage(this.lineBuf); } private void parseHeader() throws IOException { final CharArrayBuffer current = this.lineBuf; final int count = this.headerBufs.size(); if ((this.lineBuf.charAt(0) == ' ' || this.lineBuf.charAt(0) == '\t') && count > 0) { // Handle folded header line final CharArrayBuffer previous = this.headerBufs.get(count - 1); int i = 0; while (i < current.length()) { final char ch = current.charAt(i); if (ch != ' ' && ch != '\t') { break; } i++; } final int maxLineLen = this.constraints.getMaxLineLength(); 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 { this.headerBufs.add(current); this.lineBuf = null; } } @Override public T parse() throws IOException, HttpException { while (this.state != COMPLETED) { if (this.lineBuf == null) { this.lineBuf = new CharArrayBuffer(64); } else { this.lineBuf.clear(); } final boolean lineComplete = this.sessionBuffer.readLine(this.lineBuf, this.endOfStream); final int maxLineLen = this.constraints.getMaxLineLength(); if (maxLineLen > 0 && (this.lineBuf.length() > maxLineLen || (!lineComplete && this.sessionBuffer.length() > maxLineLen))) { throw new MessageConstraintException("Maximum line length limit exceeded"); } if (!lineComplete) { break; } switch (this.state) { case READ_HEAD_LINE: try { parseHeadLine(); } catch (final ParseException px) { throw new ProtocolException(px.getMessage(), px); } this.state = READ_HEADERS; break; case READ_HEADERS: if (this.lineBuf.length() > 0) { final int maxHeaderCount = this.constraints.getMaxHeaderCount(); if (maxHeaderCount > 0 && headerBufs.size() >= maxHeaderCount) { throw new MessageConstraintException("Maximum header count exceeded"); } parseHeader(); } else { this.state = COMPLETED; } break; } if (this.endOfStream && !this.sessionBuffer.hasData()) { this.state = COMPLETED; } } if (this.state == COMPLETED) { for (final CharArrayBuffer buffer : this.headerBufs) { try { this.message.addHeader(lineParser.parseHeader(buffer)); } catch (final ParseException ex) { throw new ProtocolException(ex.getMessage(), ex); } } return this.message; } else { return null; } } } ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/IdentityEncoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/IdentityEncoder0100644 0000000 0000000 00000012317 12613456025 032335 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.nio.FileContentEncoder; import org.apache.http.nio.reactor.SessionOutputBuffer; /** * Content encoder 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. *

* This decoder is optimized to transfer data directly from * a {@link FileChannel} to the underlying I/O session's channel whenever * possible avoiding intermediate buffering in the session buffer. * * @since 4.0 */ @NotThreadSafe public class IdentityEncoder extends AbstractContentEncoder implements FileContentEncoder { private final int fragHint; /** * @since 4.3 * * @param channel underlying channel. * @param buffer session buffer. * @param metrics transport metrics. * @param fragementSizeHint fragment size hint defining an minimal size of a fragment * that should be written out directly to the channel bypassing the session buffer. * Value {@code 0} disables fragment buffering. */ public IdentityEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics, final int fragementSizeHint) { super(channel, buffer, metrics); this.fragHint = fragementSizeHint > 0 ? fragementSizeHint : 0; } public IdentityEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { this(channel, buffer, metrics, 0); } @Override public int write(final ByteBuffer src) throws IOException { if (src == null) { return 0; } assertNotCompleted(); int total = 0; while (src.hasRemaining()) { if (this.buffer.hasData() || this.fragHint > 0) { if (src.remaining() <= this.fragHint) { final int capacity = this.fragHint - this.buffer.length(); if (capacity > 0) { final int limit = Math.min(capacity, src.remaining()); final int bytesWritten = writeToBuffer(src, limit); total += bytesWritten; } } } if (this.buffer.hasData()) { if (this.buffer.length() >= this.fragHint || src.hasRemaining()) { final int bytesWritten = flushToChannel(); if (bytesWritten == 0) { break; } } } if (!this.buffer.hasData() && src.remaining() > this.fragHint) { final int bytesWritten = writeToChannel(src); total += bytesWritten; if (bytesWritten == 0) { break; } } } return total; } @Override public long transfer( final FileChannel src, final long position, final long count) throws IOException { if (src == null) { return 0; } assertNotCompleted(); flushToChannel(); if (this.buffer.hasData()) { return 0; } final long bytesWritten = src.transferTo(position, count, this.channel); if (bytesWritten > 0) { this.metrics.incrementBytesTransferred(bytesWritten); } return bytesWritten; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("[identity; completed: "); sb.append(isCompleted()); sb.append("]"); return sb.toString(); } } ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimitedDecoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimited0100644 0000000 0000000 00000013530 12613456025 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.impl.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import org.apache.http.ConnectionClosedException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.nio.FileContentDecoder; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.util.Args; /** * Content decoder that cuts off after a defined number of bytes. This class * is used to receive content of HTTP messages where the end of the content * entity is determined by the value of the {@code Content-Length header}. * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE} * long. *

* This decoder is optimized to transfer data directly from the underlying * I/O session's channel to a {@link FileChannel}, whenever * possible avoiding intermediate buffering in the session buffer. * * @since 4.0 */ @NotThreadSafe public class LengthDelimitedDecoder extends AbstractContentDecoder implements FileContentDecoder { private final long contentLength; private long len; public LengthDelimitedDecoder( final ReadableByteChannel channel, final SessionInputBuffer buffer, final HttpTransportMetricsImpl metrics, final long contentLength) { super(channel, buffer, metrics); Args.notNegative(contentLength, "Content length"); this.contentLength = contentLength; } @Override public int read(final ByteBuffer dst) throws IOException { Args.notNull(dst, "Byte buffer"); if (this.completed) { return -1; } final int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE); final int bytesRead; if (this.buffer.hasData()) { final int maxLen = Math.min(chunk, this.buffer.length()); bytesRead = this.buffer.read(dst, maxLen); } else { bytesRead = readFromChannel(dst, chunk); } if (bytesRead == -1) { this.completed = true; if (this.len < this.contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + this.contentLength + "; received: " + this.len); } } this.len += bytesRead; if (this.len >= this.contentLength) { this.completed = true; } if (this.completed && bytesRead == 0) { return -1; } else { return bytesRead; } } @Override public long transfer( final FileChannel dst, final long position, final long count) throws IOException { if (dst == null) { return 0; } if (this.completed) { return -1; } final int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE); final long bytesRead; if (this.buffer.hasData()) { final int maxLen = Math.min(chunk, this.buffer.length()); dst.position(position); bytesRead = this.buffer.read(dst, maxLen); } else { if (this.channel.isOpen()) { if (position > dst.size()) { throw new IOException("Position past end of file [" + position + " > " + dst.size() + "]"); } bytesRead = dst.transferFrom(this.channel, position, count < chunk ? count : chunk); } else { bytesRead = -1; } if (bytesRead > 0) { this.metrics.incrementBytesTransferred(bytesRead); } } if (bytesRead == -1) { this.completed = true; if (this.len < this.contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + this.contentLength + "; received: " + this.len); } } this.len += bytesRead; if (this.len >= this.contentLength) { this.completed = true; } return bytesRead; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("[content length: "); sb.append(this.contentLength); sb.append("; pos: "); sb.append(this.len); sb.append("; completed: "); sb.append(this.completed); sb.append("]"); return sb.toString(); } } ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/IdentityDecoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/IdentityDecoder0100644 0000000 0000000 00000011341 12613456025 032317 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.nio.FileContentDecoder; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.util.Args; /** * Content decoder that reads data without any transformation. The end of the * content entity is delineated by closing the underlying connection * (EOF condition). Entities transferred using this input stream can be of * unlimited length. *

* This decoder is optimized to transfer data directly from the underlying * I/O session's channel to a {@link FileChannel}, whenever * possible avoiding intermediate buffering in the session buffer. * * @since 4.0 */ @NotThreadSafe public class IdentityDecoder extends AbstractContentDecoder implements FileContentDecoder { public IdentityDecoder( final ReadableByteChannel channel, final SessionInputBuffer buffer, final HttpTransportMetricsImpl metrics) { super(channel, buffer, metrics); } /** * Sets the completed status of this decoder. Normally this is not necessary * (the decoder will automatically complete when the underlying channel * returns EOF). It is useful to mark the decoder as completed if you have * some other means to know all the necessary data has been read and want to * reuse the underlying connection for more messages. */ public void setCompleted(final boolean completed) { this.completed = completed; } @Override public int read(final ByteBuffer dst) throws IOException { Args.notNull(dst, "Byte buffer"); if (this.completed) { return -1; } final int bytesRead; if (this.buffer.hasData()) { bytesRead = this.buffer.read(dst); } else { bytesRead = readFromChannel(dst); } if (bytesRead == -1) { this.completed = true; } return bytesRead; } @Override public long transfer( final FileChannel dst, final long position, final long count) throws IOException { if (dst == null) { return 0; } if (this.completed) { return 0; } long bytesRead; if (this.buffer.hasData()) { dst.position(position); bytesRead = this.buffer.read(dst); } else { if (this.channel.isOpen()) { if (position > dst.size()) { throw new IOException("Position past end of file [" + position + " > " + dst.size() + "]"); } bytesRead = dst.transferFrom(this.channel, position, count); if (count > 0 && bytesRead == 0) { bytesRead = this.buffer.fill(this.channel); } } else { bytesRead = -1; } if (bytesRead > 0) { this.metrics.incrementBytesTransferred(bytesRead); } } if (bytesRead == -1) { this.completed = true; } return bytesRead; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("[identity; completed: "); sb.append(this.completed); sb.append("]"); return sb.toString(); } } ././@LongLink0100644 0000000 0000000 00000000163 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequestWriter.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequ0100644 0000000 0000000 00000006001 12613456025 032316 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import org.apache.http.HttpRequest; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.message.LineFormatter; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.CharArrayBuffer; /** * Default {@link org.apache.http.nio.NHttpMessageWriter} implementation * for {@link HttpRequest}s. * * @since 4.1 */ @SuppressWarnings("deprecation") @NotThreadSafe public class DefaultHttpRequestWriter extends AbstractMessageWriter { /** * @deprecated (4.3) use * {@link DefaultHttpRequestWriter#DefaultHttpRequestWriter(SessionOutputBuffer, LineFormatter)} */ @Deprecated public DefaultHttpRequestWriter(final SessionOutputBuffer buffer, final LineFormatter formatter, final HttpParams params) { super(buffer, formatter, params); } /** * Creates an instance of DefaultHttpRequestWriter. * * @param buffer the session output buffer. * @param formatter the line formatter If {@code null} * {@link org.apache.http.message.BasicLineFormatter#INSTANCE} will be used. * * @since 4.3 */ public DefaultHttpRequestWriter( final SessionOutputBuffer buffer, final LineFormatter formatter) { super(buffer, formatter); } /** * @since 4.3 */ public DefaultHttpRequestWriter(final SessionOutputBuffer buffer) { super(buffer, null); } @Override protected void writeHeadLine(final HttpRequest message) throws IOException { final CharArrayBuffer buffer = lineFormatter.formatRequestLine( this.lineBuf, message.getRequestLine()); this.sessionBuffer.writeLine(buffer); } } ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractContentDecoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractContent0100644 0000000 0000000 00000010574 12613456025 032345 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.util.Args; /** * Abstract {@link ContentDecoder} that serves as a base for all content * decoder implementations. * * @since 4.0 */ @NotThreadSafe public abstract class AbstractContentDecoder implements ContentDecoder { protected final ReadableByteChannel channel; protected final SessionInputBuffer buffer; protected final HttpTransportMetricsImpl metrics; protected boolean completed; /** * Creates an instance of this class. * * @param channel the source channel. * @param buffer the session input buffer that can be used to store * session data for intermediate processing. * @param metrics Transport metrics of the underlying HTTP transport. */ public AbstractContentDecoder( final ReadableByteChannel channel, final SessionInputBuffer buffer, final HttpTransportMetricsImpl metrics) { super(); Args.notNull(channel, "Channel"); Args.notNull(buffer, "Session input buffer"); Args.notNull(metrics, "Transport metrics"); this.buffer = buffer; this.channel = channel; this.metrics = metrics; } @Override public boolean isCompleted() { return this.completed; } /** * Reads from the channel to the destination. * * @param dst destination. * @return number of bytes transferred. * * @since 4.3 */ protected int readFromChannel(final ByteBuffer dst) throws IOException { final int bytesRead = this.channel.read(dst); if (bytesRead > 0) { this.metrics.incrementBytesTransferred(bytesRead); } return bytesRead; } /** * Reads from the channel to the session buffer. * @return number of bytes transferred. * * @since 4.3 */ protected int fillBufferFromChannel() throws IOException { final int bytesRead = this.buffer.fill(this.channel); if (bytesRead > 0) { this.metrics.incrementBytesTransferred(bytesRead); } return bytesRead; } /** * Reads from the channel to the destination. * * @param dst destination. * @param limit max number of bytes to transfer. * @return number of bytes transferred. * * @since 4.3 */ protected int readFromChannel(final ByteBuffer dst, final int limit) throws IOException { final int bytesRead; if (dst.remaining() > limit) { final int oldLimit = dst.limit(); final int newLimit = oldLimit - (dst.remaining() - limit); dst.limit(newLimit); bytesRead = this.channel.read(dst); dst.limit(oldLimit); } else { bytesRead = this.channel.read(dst); } if (bytesRead > 0) { this.metrics.incrementBytesTransferred(bytesRead); } return bytesRead; } } ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractContentEncoder.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractContent0100644 0000000 0000000 00000013600 12613456025 032336 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * Abstract {@link ContentEncoder} that serves as a base for all content * encoder implementations. * * @since 4.0 */ @NotThreadSafe public abstract class AbstractContentEncoder implements ContentEncoder { protected final WritableByteChannel channel; protected final SessionOutputBuffer buffer; protected final HttpTransportMetricsImpl metrics; /** * TODO: make private */ protected boolean completed; /** * Creates an instance of this class. * * @param channel the destination channel. * @param buffer the session output buffer that can be used to store * session data for intermediate processing. * @param metrics Transport metrics of the underlying HTTP transport. */ public AbstractContentEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { super(); Args.notNull(channel, "Channel"); Args.notNull(buffer, "Session input buffer"); Args.notNull(metrics, "Transport metrics"); this.buffer = buffer; this.channel = channel; this.metrics = metrics; } @Override public boolean isCompleted() { return this.completed; } @Override public void complete() throws IOException { this.completed = true; } protected void assertNotCompleted() { Asserts.check(!this.completed, "Encoding process already completed"); } /** * Flushes content of the session buffer to the channel and updates transport metrics. * * @return number of bytes written to the channel. * * @since 4.3 */ protected int flushToChannel() throws IOException { if (!this.buffer.hasData()) { return 0; } final int bytesWritten = this.buffer.flush(this.channel); if (bytesWritten > 0) { this.metrics.incrementBytesTransferred(bytesWritten); } return bytesWritten; } /** * Flushes content of the given buffer to the channel and updates transport metrics. * * @return number of bytes written to the channel. * * @since 4.3 */ protected int writeToChannel(final ByteBuffer src) throws IOException { if (!src.hasRemaining()) { return 0; } final int bytesWritten = this.channel.write(src); if (bytesWritten > 0) { this.metrics.incrementBytesTransferred(bytesWritten); } return bytesWritten; } /** * Transfers content of the source to the channel and updates transport metrics. * * @param src source. * @param limit max number of bytes to transfer. * @return number of bytes transferred. * * @since 4.3 */ protected int writeToChannel(final ByteBuffer src, final int limit) throws IOException { return doWriteChunk(src, limit, true); } /** * Transfers content of the source to the buffer and updates transport metrics. * * @param src source. * @param limit max number of bytes to transfer. * @return number of bytes transferred. * * @since 4.3 */ protected int writeToBuffer(final ByteBuffer src, final int limit) throws IOException { return doWriteChunk(src, limit, false); } private int doWriteChunk( final ByteBuffer src, final int chunk, final boolean direct) throws IOException { final int bytesWritten; if (src.remaining() > chunk) { final int oldLimit = src.limit(); final int newLimit = oldLimit - (src.remaining() - chunk); src.limit(newLimit); bytesWritten = doWriteChunk(src, direct); src.limit(oldLimit); } else { bytesWritten = doWriteChunk(src, direct); } return bytesWritten; } private int doWriteChunk(final ByteBuffer src, final boolean direct) throws IOException { if (direct) { final int bytesWritten = this.channel.write(src); if (bytesWritten > 0) { this.metrics.incrementBytesTransferred(bytesWritten); } return bytesWritten; } else { final int chunk = src.remaining(); this.buffer.write(src); return chunk; } } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/0040755 0000000 0000000 00000000000 12613456025 027031 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/BasicNIOConnPool.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/BasicNIOConnPool.0100644 0000000 0000000 00000015652 12613456025 032077 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.pool; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.apache.http.HttpHost; import org.apache.http.annotation.ThreadSafe; import org.apache.http.concurrent.FutureCallback; import org.apache.http.config.ConnectionConfig; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.pool.AbstractNIOConnPool; import org.apache.http.nio.pool.NIOConnFactory; import org.apache.http.nio.pool.SocketAddressResolver; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * A very basic {@link org.apache.http.pool.ConnPool} implementation that * represents a pool of non-blocking {@link NHttpClientConnection} 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 BasicNIOConnPool extends AbstractNIOConnPool { private static final AtomicLong COUNTER = new AtomicLong(); private final int connectTimeout; static class BasicAddressResolver implements SocketAddressResolver { @Override public SocketAddress resolveLocalAddress(final HttpHost host) { return null; } @Override public SocketAddress resolveRemoteAddress(final HttpHost host) { 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; } } return new InetSocketAddress(hostname, port); } } /** * @deprecated (4.3) use {@link BasicNIOConnPool#BasicNIOConnPool(ConnectingIOReactor, NIOConnFactory, int)} */ @Deprecated public BasicNIOConnPool( final ConnectingIOReactor ioreactor, final NIOConnFactory connFactory, final HttpParams params) { super(ioreactor, connFactory, 2, 20); Args.notNull(params, "HTTP parameters"); this.connectTimeout = params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0); } /** * @deprecated (4.3) use {@link BasicNIOConnPool#BasicNIOConnPool(ConnectingIOReactor, * ConnectionConfig)} */ @Deprecated public BasicNIOConnPool( final ConnectingIOReactor ioreactor, final HttpParams params) { this(ioreactor, new BasicNIOConnFactory(params), params); } /** * @since 4.3 */ public BasicNIOConnPool( final ConnectingIOReactor ioreactor, final NIOConnFactory connFactory, final int connectTimeout) { super(ioreactor, connFactory, new BasicAddressResolver(), 2, 20); this.connectTimeout = connectTimeout; } /** * @since 4.3 */ public BasicNIOConnPool( final ConnectingIOReactor ioreactor, final int connectTimeout, final ConnectionConfig config) { this(ioreactor, new BasicNIOConnFactory(config), connectTimeout); } /** * @since 4.3 */ public BasicNIOConnPool( final ConnectingIOReactor ioreactor, final ConnectionConfig config) { this(ioreactor, new BasicNIOConnFactory(config), 0); } /** * @since 4.3 */ public BasicNIOConnPool(final ConnectingIOReactor ioreactor) { this(ioreactor, new BasicNIOConnFactory(ConnectionConfig.DEFAULT), 0); } /** * @deprecated (4.3) use {@link SocketAddressResolver} */ @Deprecated @Override protected SocketAddress resolveRemoteAddress(final HttpHost host) { return new InetSocketAddress(host.getHostName(), host.getPort()); } /** * @deprecated (4.3) use {@link SocketAddressResolver} */ @Deprecated @Override protected SocketAddress resolveLocalAddress(final HttpHost host) { return null; } @Override protected BasicNIOPoolEntry createEntry(final HttpHost host, final NHttpClientConnection conn) { final BasicNIOPoolEntry entry = new BasicNIOPoolEntry( Long.toString(COUNTER.getAndIncrement()), host, conn); entry.setSocketTimeout(conn.getSocketTimeout()); return entry; } @Override public Future lease( final HttpHost route, final Object state, final FutureCallback callback) { return super.lease(route, state, this.connectTimeout, TimeUnit.MILLISECONDS, callback); } @Override public Future lease( final HttpHost route, final Object state) { return super.lease(route, state, this.connectTimeout, TimeUnit.MILLISECONDS, null); } @Override protected void onLease(final BasicNIOPoolEntry entry) { final NHttpClientConnection conn = entry.getConnection(); conn.setSocketTimeout(entry.getSocketTimeout()); } @Override protected void onRelease(final BasicNIOPoolEntry entry) { final NHttpClientConnection conn = entry.getConnection(); entry.setSocketTimeout(conn.getSocketTimeout()); conn.setSocketTimeout(0); } } ././@LongLink0100644 0000000 0000000 00000000145 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/package-info.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/package-info.java0100644 0000000 0000000 00000002473 12613456025 032223 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 asynchronous, even driven communication. */ package org.apache.http.impl.nio.pool; ././@LongLink0100644 0000000 0000000 00000000154 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/BasicNIOConnFactory.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/BasicNIOConnFacto0100644 0000000 0000000 00000014667 12613456025 032151 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.pool; import java.io.IOException; import javax.net.ssl.SSLContext; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.annotation.Immutable; import org.apache.http.config.ConnectionConfig; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultNHttpClientConnectionFactory; import org.apache.http.impl.nio.SSLNHttpClientConnectionFactory; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpConnectionFactory; import org.apache.http.nio.NHttpMessageParserFactory; import org.apache.http.nio.NHttpMessageWriterFactory; import org.apache.http.nio.pool.NIOConnFactory; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ssl.SSLSetupHandler; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * A basic {@link NIOConnFactory} implementation that creates * {@link NHttpClientConnection} instances given a {@link HttpHost} instance. * * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable public class BasicNIOConnFactory implements NIOConnFactory { private final NHttpConnectionFactory plainFactory; private final NHttpConnectionFactory sslFactory; public BasicNIOConnFactory( final NHttpConnectionFactory plainFactory, final NHttpConnectionFactory sslFactory) { super(); Args.notNull(plainFactory, "Plain HTTP client connection factory"); this.plainFactory = plainFactory; this.sslFactory = sslFactory; } public BasicNIOConnFactory( final NHttpConnectionFactory plainFactory) { this(plainFactory, null); } /** * @deprecated (4.3) use {@link BasicNIOConnFactory#BasicNIOConnFactory(SSLContext, * SSLSetupHandler, NHttpMessageParserFactory, NHttpMessageWriterFactory, * ByteBufferAllocator, ConnectionConfig)} */ @Deprecated public BasicNIOConnFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpResponseFactory responseFactory, final ByteBufferAllocator allocator, final HttpParams params) { this(new DefaultNHttpClientConnectionFactory( responseFactory, allocator, params), new SSLNHttpClientConnectionFactory( sslcontext, sslHandler, responseFactory, allocator, params)); } /** * @deprecated (4.3) use {@link BasicNIOConnFactory#BasicNIOConnFactory(SSLContext, * SSLSetupHandler, ConnectionConfig)} */ @Deprecated public BasicNIOConnFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { this(sslcontext, sslHandler, DefaultHttpResponseFactory.INSTANCE, HeapByteBufferAllocator.INSTANCE, params); } /** * @deprecated (4.3) use {@link BasicNIOConnFactory#BasicNIOConnFactory(ConnectionConfig)} */ @Deprecated public BasicNIOConnFactory(final HttpParams params) { this(null, null, params); } /** * @since 4.3 */ public BasicNIOConnFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final NHttpMessageParserFactory responseParserFactory, final NHttpMessageWriterFactory requestWriterFactory, final ByteBufferAllocator allocator, final ConnectionConfig config) { this(new DefaultNHttpClientConnectionFactory( responseParserFactory, requestWriterFactory, allocator, config), new SSLNHttpClientConnectionFactory( sslcontext, sslHandler, responseParserFactory, requestWriterFactory, allocator, config)); } /** * @since 4.3 */ public BasicNIOConnFactory( final SSLContext sslcontext, final SSLSetupHandler sslHandler, final ConnectionConfig config) { this(sslcontext, sslHandler, null, null, null, config); } /** * @since 4.3 */ public BasicNIOConnFactory(final ConnectionConfig config) { this(new DefaultNHttpClientConnectionFactory(config), null); } @Override public NHttpClientConnection create(final HttpHost route, final IOSession session) throws IOException { final NHttpClientConnection conn; if (route.getSchemeName().equalsIgnoreCase("https")) { if (this.sslFactory == null) { throw new IOException("SSL not supported"); } conn = this.sslFactory.createConnection(session); } else { conn = this.plainFactory.createConnection(session); } session.setAttribute(IOEventDispatch.CONNECTION_KEY, conn); return conn; } } ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/BasicNIOPoolEntry.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/pool/BasicNIOPoolEntry0100644 0000000 0000000 00000004445 12613456025 032223 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.pool; import java.io.IOException; import org.apache.http.HttpHost; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.pool.PoolEntry; /** * A basic {@link PoolEntry} implementation that represents an entry * in a pool of non-blocking {@link NHttpClientConnection}s identified by * an {@link HttpHost} instance. * * @see HttpHost * @since 4.2 */ @ThreadSafe public class BasicNIOPoolEntry extends PoolEntry { private volatile int socketTimeout; public BasicNIOPoolEntry(final String id, final HttpHost route, final NHttpClientConnection conn) { super(id, route, conn); } @Override public void close() { try { getConnection().close(); } catch (final IOException ignore) { } } @Override public boolean isClosed() { return !getConnection().isOpen(); } int getSocketTimeout() { return socketTimeout; } void setSocketTimeout(final int socketTimeout) { this.socketTimeout = socketTimeout; } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/0040755 0000000 0000000 00000000000 12613456025 027517 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ListenerEndpointImpl.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ListenerEndpoi0100644 0000000 0000000 00000010304 12613456025 032361 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.Channel; import java.nio.channels.SelectionKey; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.util.Args; /** * Default implementation of {@link ListenerEndpoint}. * * @since 4.0 */ @ThreadSafe public class ListenerEndpointImpl implements ListenerEndpoint { private volatile boolean completed; private volatile boolean closed; private volatile SelectionKey key; private volatile SocketAddress address; private volatile IOException exception; private final ListenerEndpointClosedCallback callback; public ListenerEndpointImpl( final SocketAddress address, final ListenerEndpointClosedCallback callback) { super(); Args.notNull(address, "Address"); this.address = address; this.callback = callback; } @Override public SocketAddress getAddress() { return this.address; } public boolean isCompleted() { return this.completed; } @Override public IOException getException() { return this.exception; } @Override public void waitFor() throws InterruptedException { if (this.completed) { return; } synchronized (this) { while (!this.completed) { wait(); } } } public void completed(final SocketAddress address) { Args.notNull(address, "Address"); if (this.completed) { return; } this.completed = true; synchronized (this) { this.address = address; notifyAll(); } } public void failed(final IOException exception) { if (exception == null) { return; } if (this.completed) { return; } this.completed = true; synchronized (this) { this.exception = exception; notifyAll(); } } public void cancel() { if (this.completed) { return; } this.completed = true; this.closed = true; synchronized (this) { notifyAll(); } } protected void setKey(final SelectionKey key) { this.key = key; } @Override public boolean isClosed() { return this.closed || (this.key != null && !this.key.isValid()); } @Override public void close() { if (this.closed) { return; } this.completed = true; this.closed = true; if (this.key != null) { this.key.cancel(); final Channel channel = this.key.channel(); try { channel.close(); } catch (final IOException ignore) {} } if (this.callback != null) { this.callback.endpointClosed(this); } synchronized (this) { notifyAll(); } } } ././@LongLink0100644 0000000 0000000 00000000166 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/DefaultConnectingIOReactor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/DefaultConnect0100644 0000000 0000000 00000025361 12613456025 032344 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ThreadFactory; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.params.HttpParams; import org.apache.http.util.Asserts; /** * Default implementation of {@link ConnectingIOReactor}. This class extends * {@link AbstractMultiworkerIOReactor} with capability to connect to remote * hosts. * * @since 4.0 */ @SuppressWarnings("deprecation") @ThreadSafe // public methods only public class DefaultConnectingIOReactor extends AbstractMultiworkerIOReactor implements ConnectingIOReactor { private final Queue requestQueue; private long lastTimeoutCheck; /** * Creates an instance of DefaultConnectingIOReactor with the given configuration. * * @param config I/O reactor configuration. * @param threadFactory the factory to create threads. * Can be {@code null}. * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.2 */ public DefaultConnectingIOReactor( final IOReactorConfig config, final ThreadFactory threadFactory) throws IOReactorException { super(config, threadFactory); this.requestQueue = new ConcurrentLinkedQueue(); this.lastTimeoutCheck = System.currentTimeMillis(); } /** * Creates an instance of DefaultConnectingIOReactor with the given configuration. * * @param config I/O reactor configuration. * Can be {@code null}. * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.2 */ public DefaultConnectingIOReactor(final IOReactorConfig config) throws IOReactorException { this(config, null); } /** * Creates an instance of DefaultConnectingIOReactor with default configuration. * * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.2 */ public DefaultConnectingIOReactor() throws IOReactorException { this(null, null); } /** * @deprecated (4.2) use {@link DefaultConnectingIOReactor#DefaultConnectingIOReactor(IOReactorConfig, ThreadFactory)} */ @Deprecated public DefaultConnectingIOReactor( final int workerCount, final ThreadFactory threadFactory, final HttpParams params) throws IOReactorException { this(convert(workerCount, params), threadFactory); } /** * @deprecated (4.2) use {@link DefaultConnectingIOReactor#DefaultConnectingIOReactor(IOReactorConfig)} */ @Deprecated public DefaultConnectingIOReactor( final int workerCount, final HttpParams params) throws IOReactorException { this(convert(workerCount, params), null); } @Override protected void cancelRequests() throws IOReactorException { SessionRequestImpl request; while ((request = this.requestQueue.poll()) != null) { request.cancel(); } } @Override protected void processEvents(final int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { final Set selectedKeys = this.selector.selectedKeys(); for (final SelectionKey key : selectedKeys) { processEvent(key); } selectedKeys.clear(); } final long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; final Set keys = this.selector.keys(); processTimeouts(keys); } } private void processEvent(final SelectionKey key) { try { if (key.isConnectable()) { final SocketChannel channel = (SocketChannel) key.channel(); // Get request handle final SessionRequestHandle requestHandle = (SessionRequestHandle) key.attachment(); final SessionRequestImpl sessionRequest = requestHandle.getSessionRequest(); // Finish connection process try { channel.finishConnect(); } catch (final IOException ex) { sessionRequest.failed(ex); } key.cancel(); key.attach(null); if (!sessionRequest.isCompleted()) { addChannel(new ChannelEntry(channel, sessionRequest)); } else { try { channel.close(); } catch (IOException ignore) { } } } } catch (final CancelledKeyException ex) { final SessionRequestHandle requestHandle = (SessionRequestHandle) key.attachment(); key.attach(null); if (requestHandle != null) { final SessionRequestImpl sessionRequest = requestHandle.getSessionRequest(); if (sessionRequest != null) { sessionRequest.cancel(); } } } } private void processTimeouts(final Set keys) { final long now = System.currentTimeMillis(); for (final SelectionKey key : keys) { final Object attachment = key.attachment(); if (attachment instanceof SessionRequestHandle) { final SessionRequestHandle handle = (SessionRequestHandle) key.attachment(); final SessionRequestImpl sessionRequest = handle.getSessionRequest(); final int timeout = sessionRequest.getConnectTimeout(); if (timeout > 0) { if (handle.getRequestTime() + timeout < now) { sessionRequest.timeout(); } } } } } @Override public SessionRequest connect( final SocketAddress remoteAddress, final SocketAddress localAddress, final Object attachment, final SessionRequestCallback callback) { Asserts.check(this.status.compareTo(IOReactorStatus.ACTIVE) <= 0, "I/O reactor has been shut down"); final SessionRequestImpl sessionRequest = new SessionRequestImpl( remoteAddress, localAddress, attachment, callback); sessionRequest.setConnectTimeout(this.config.getConnectTimeout()); this.requestQueue.add(sessionRequest); this.selector.wakeup(); return sessionRequest; } private void validateAddress(final SocketAddress address) throws UnknownHostException { if (address == null) { return; } if (address instanceof InetSocketAddress) { final InetSocketAddress endpoint = (InetSocketAddress) address; if (endpoint.isUnresolved()) { throw new UnknownHostException(endpoint.getHostName()); } } } private void processSessionRequests() throws IOReactorException { SessionRequestImpl request; while ((request = this.requestQueue.poll()) != null) { if (request.isCompleted()) { continue; } final SocketChannel socketChannel; try { socketChannel = SocketChannel.open(); } catch (final IOException ex) { throw new IOReactorException("Failure opening socket", ex); } try { validateAddress(request.getLocalAddress()); validateAddress(request.getRemoteAddress()); socketChannel.configureBlocking(false); prepareSocket(socketChannel.socket()); if (request.getLocalAddress() != null) { final Socket sock = socketChannel.socket(); sock.setReuseAddress(this.config.isSoReuseAddress()); sock.bind(request.getLocalAddress()); } final boolean connected = socketChannel.connect(request.getRemoteAddress()); if (connected) { final ChannelEntry entry = new ChannelEntry(socketChannel, request); addChannel(entry); continue; } } catch (final IOException ex) { closeChannel(socketChannel); request.failed(ex); return; } final SessionRequestHandle requestHandle = new SessionRequestHandle(request); try { final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT, requestHandle); request.setKey(key); } catch (final IOException ex) { closeChannel(socketChannel); throw new IOReactorException("Failure registering channel " + "with the selector", ex); } } } } ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/IOSessionImpl.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/IOSessionImpl.0100644 0000000 0000000 00000027312 12613456025 032217 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionBufferStatus; import org.apache.http.nio.reactor.SocketAccessor; import org.apache.http.util.Args; /** * Default implementation of {@link IOSession}. * * @since 4.0 */ @ThreadSafe public class IOSessionImpl implements IOSession, SocketAccessor { private final SelectionKey key; private final ByteChannel channel; private final Map attributes; private final InterestOpsCallback interestOpsCallback; private final SessionClosedCallback sessionClosedCallback; private volatile int status; private volatile int currentEventMask; private volatile SessionBufferStatus bufferStatus; private volatile int socketTimeout; private final long startedTime; private volatile long lastReadTime; private volatile long lastWriteTime; private volatile long lastAccessTime; /** * Creates new instance of IOSessionImpl. * * @param key the selection key. * @param interestOpsCallback interestOps callback. * @param sessionClosedCallback session closed callback. * * @since 4.1 */ public IOSessionImpl( final SelectionKey key, final InterestOpsCallback interestOpsCallback, final SessionClosedCallback sessionClosedCallback) { super(); Args.notNull(key, "Selection key"); this.key = key; this.channel = (ByteChannel) this.key.channel(); this.interestOpsCallback = interestOpsCallback; this.sessionClosedCallback = sessionClosedCallback; this.attributes = Collections.synchronizedMap(new HashMap()); this.currentEventMask = key.interestOps(); this.socketTimeout = 0; this.status = ACTIVE; final long now = System.currentTimeMillis(); this.startedTime = now; this.lastReadTime = now; this.lastWriteTime = now; this.lastAccessTime = now; } /** * Creates new instance of IOSessionImpl. * * @param key the selection key. * @param sessionClosedCallback session closed callback. */ public IOSessionImpl( final SelectionKey key, final SessionClosedCallback sessionClosedCallback) { this(key, null, sessionClosedCallback); } @Override public ByteChannel channel() { return this.channel; } @Override public SocketAddress getLocalAddress() { if (this.channel instanceof SocketChannel) { return ((SocketChannel)this.channel).socket().getLocalSocketAddress(); } else { return null; } } @Override public SocketAddress getRemoteAddress() { if (this.channel instanceof SocketChannel) { return ((SocketChannel)this.channel).socket().getRemoteSocketAddress(); } else { return null; } } @Override public int getEventMask() { return this.interestOpsCallback != null ? this.currentEventMask : this.key.interestOps(); } @Override public synchronized void setEventMask(final int ops) { if (this.status == CLOSED) { return; } if (this.interestOpsCallback != null) { // update the current event mask this.currentEventMask = ops; // local variable final InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask); // add this operation to the interestOps() queue this.interestOpsCallback.addInterestOps(entry); } else { this.key.interestOps(ops); } this.key.selector().wakeup(); } @Override public synchronized void setEvent(final int op) { if (this.status == CLOSED) { return; } if (this.interestOpsCallback != null) { // update the current event mask this.currentEventMask |= op; // local variable final InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask); // add this operation to the interestOps() queue this.interestOpsCallback.addInterestOps(entry); } else { final int ops = this.key.interestOps(); this.key.interestOps(ops | op); } this.key.selector().wakeup(); } @Override public synchronized void clearEvent(final int op) { if (this.status == CLOSED) { return; } if (this.interestOpsCallback != null) { // update the current event mask this.currentEventMask &= ~op; // local variable final InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask); // add this operation to the interestOps() queue this.interestOpsCallback.addInterestOps(entry); } else { final int ops = this.key.interestOps(); this.key.interestOps(ops & ~op); } this.key.selector().wakeup(); } @Override public int getSocketTimeout() { return this.socketTimeout; } @Override public void setSocketTimeout(final int timeout) { this.socketTimeout = timeout; this.lastAccessTime = System.currentTimeMillis(); } @Override public void close() { synchronized (this) { if (this.status == CLOSED) { return; } this.status = CLOSED; } synchronized (this.key) { this.key.cancel(); try { this.key.channel().close(); } catch (final IOException ex) { // Munching exceptions is not nice // but in this case it is justified } if (this.sessionClosedCallback != null) { this.sessionClosedCallback.sessionClosed(this); } if (this.key.selector().isOpen()) { this.key.selector().wakeup(); } } } @Override public int getStatus() { return this.status; } @Override public boolean isClosed() { return this.status == CLOSED; } @Override public void shutdown() { // For this type of session, a close() does exactly // what we need and nothing more. close(); } @Override public boolean hasBufferedInput() { final SessionBufferStatus buffStatus = this.bufferStatus; return buffStatus != null && buffStatus.hasBufferedInput(); } @Override public boolean hasBufferedOutput() { final SessionBufferStatus buffStatus = this.bufferStatus; return buffStatus != null && buffStatus.hasBufferedOutput(); } @Override public void setBufferStatus(final SessionBufferStatus bufferStatus) { this.bufferStatus = bufferStatus; } @Override public Object getAttribute(final String name) { return this.attributes.get(name); } @Override public Object removeAttribute(final String name) { return this.attributes.remove(name); } @Override public void setAttribute(final String name, final Object obj) { this.attributes.put(name, obj); } public long getStartedTime() { return this.startedTime; } public long getLastReadTime() { return this.lastReadTime; } public long getLastWriteTime() { return this.lastWriteTime; } public long getLastAccessTime() { return this.lastAccessTime; } void resetLastRead() { final long now = System.currentTimeMillis(); this.lastReadTime = now; this.lastAccessTime = now; } void resetLastWrite() { final long now = System.currentTimeMillis(); this.lastWriteTime = now; this.lastAccessTime = now; } private static void formatOps(final StringBuilder buffer, final int ops) { if ((ops & SelectionKey.OP_READ) > 0) { buffer.append('r'); } if ((ops & SelectionKey.OP_WRITE) > 0) { buffer.append('w'); } if ((ops & SelectionKey.OP_ACCEPT) > 0) { buffer.append('a'); } if ((ops & SelectionKey.OP_CONNECT) > 0) { buffer.append('c'); } } 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() { final StringBuilder buffer = new StringBuilder(); synchronized (this.key) { final SocketAddress remoteAddress = getRemoteAddress(); final SocketAddress localAddress = getLocalAddress(); if (remoteAddress != null && localAddress != null) { formatAddress(buffer, localAddress); buffer.append("<->"); formatAddress(buffer, remoteAddress); } buffer.append('['); switch (this.status) { case ACTIVE: buffer.append("ACTIVE"); break; case CLOSING: buffer.append("CLOSING"); break; case CLOSED: buffer.append("CLOSED"); break; } buffer.append("]["); if (this.key.isValid()) { formatOps(buffer, this.interestOpsCallback != null ? this.currentEventMask : this.key.interestOps()); buffer.append(':'); formatOps(buffer, this.key.readyOps()); } } buffer.append(']'); return new String(buffer); } @Override public Socket getSocket() { if (this.channel instanceof SocketChannel) { return ((SocketChannel) this.channel).socket(); } else { return null; } } } ././@LongLink0100644 0000000 0000000 00000000170 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractMultiworkerIOReactor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractMultiw0100644 0000000 0000000 00000056020 12613456025 032407 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.IOException; import java.io.InterruptedIOException; import java.net.Socket; import java.nio.channels.Channel; import java.nio.channels.ClosedChannelException; import java.nio.channels.ClosedSelectorException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.params.NIOReactorPNames; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactor; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * Generic implementation of {@link IOReactor} that can run multiple * {@link BaseIOReactor} instance in separate worker threads and distribute * newly created I/O session equally across those I/O reactors for a more * optimal resource utilization and a better I/O performance. Usually it is * recommended to have one worker I/O reactor per physical CPU core. *

* Important note about 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 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 {@link IOReactorExceptionHandler} interface. *

* 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 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 obtain the audit log using {@link #getAuditLog()}, examine exceptions * thrown by the I/O reactor prior and in the course of the reactor shutdown * and decide whether it is safe to restart the I/O reactor. * * @since 4.0 */ @SuppressWarnings("deprecation") @ThreadSafe // public methods only public abstract class AbstractMultiworkerIOReactor implements IOReactor { protected volatile IOReactorStatus status; /** * @deprecated (4.2) */ @Deprecated protected final HttpParams params; protected final IOReactorConfig config; protected final Selector selector; protected final long selectTimeout; protected final boolean interestOpsQueueing; private final int workerCount; private final ThreadFactory threadFactory; private final BaseIOReactor[] dispatchers; private final Worker[] workers; private final Thread[] threads; private final Object statusLock; //TODO: make final protected IOReactorExceptionHandler exceptionHandler; protected List auditLog; private int currentWorker = 0; /** * Creates an instance of AbstractMultiworkerIOReactor with the given configuration. * * @param config I/O reactor configuration. * @param threadFactory the factory to create threads. * Can be {@code null}. * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.2 */ public AbstractMultiworkerIOReactor( final IOReactorConfig config, final ThreadFactory threadFactory) throws IOReactorException { super(); this.config = config != null ? config : IOReactorConfig.DEFAULT; this.params = new BasicHttpParams(); try { this.selector = Selector.open(); } catch (final IOException ex) { throw new IOReactorException("Failure opening selector", ex); } this.selectTimeout = this.config.getSelectInterval(); this.interestOpsQueueing = this.config.isInterestOpQueued(); this.statusLock = new Object(); if (threadFactory != null) { this.threadFactory = threadFactory; } else { this.threadFactory = new DefaultThreadFactory(); } this.auditLog = new ArrayList(); this.workerCount = this.config.getIoThreadCount(); this.dispatchers = new BaseIOReactor[workerCount]; this.workers = new Worker[workerCount]; this.threads = new Thread[workerCount]; this.status = IOReactorStatus.INACTIVE; } /** * Creates an instance of AbstractMultiworkerIOReactor with default configuration. * * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.2 */ public AbstractMultiworkerIOReactor() throws IOReactorException { this(null, null); } @Deprecated static IOReactorConfig convert(final int workerCount, final HttpParams params) { Args.notNull(params, "HTTP parameters"); return IOReactorConfig.custom() .setSelectInterval(params.getLongParameter(NIOReactorPNames.SELECT_INTERVAL, 1000)) .setShutdownGracePeriod(params.getLongParameter(NIOReactorPNames.GRACE_PERIOD, 500)) .setInterestOpQueued(params.getBooleanParameter(NIOReactorPNames.SELECT_INTERVAL, false)) .setIoThreadCount(workerCount) .setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0)) .setConnectTimeout(params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0)) .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(); } /** * Creates an instance of AbstractMultiworkerIOReactor. * * @param workerCount number of worker I/O reactors. * @param threadFactory the factory to create threads. * Can be {@code null}. * @param params HTTP parameters. * @throws IOReactorException in case if a non-recoverable I/O error. * * @deprecated (4.2) use {@link AbstractMultiworkerIOReactor#AbstractMultiworkerIOReactor(IOReactorConfig, ThreadFactory)} */ @Deprecated public AbstractMultiworkerIOReactor( final int workerCount, final ThreadFactory threadFactory, final HttpParams params) throws IOReactorException { this(convert(workerCount, params), threadFactory); } @Override public IOReactorStatus getStatus() { return this.status; } /** * Returns the audit log containing exceptions thrown by the I/O reactor * prior and in the course of the reactor shutdown. * * @return audit log. */ public List getAuditLog() { synchronized (this.auditLog) { return new ArrayList(this.auditLog); } } /** * Adds the given {@link Throwable} object with the given time stamp * to the audit log. * * @param ex the exception thrown by the I/O reactor. * @param timestamp the time stamp of the exception. Can be * {@code null} in which case the current date / time will be used. */ protected synchronized void addExceptionEvent(final Throwable ex, final Date timestamp) { if (ex == null) { return; } synchronized (this.auditLog) { this.auditLog.add(new ExceptionEvent(ex, timestamp != null ? timestamp : new Date())); } } /** * Adds the given {@link Throwable} object to the audit log. * * @param ex the exception thrown by the I/O reactor. */ protected void addExceptionEvent(final Throwable ex) { addExceptionEvent(ex, null); } /** * Sets exception handler for this I/O reactor. * * @param exceptionHandler the exception handler. */ public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) { this.exceptionHandler = exceptionHandler; } /** * Triggered to process I/O events registered by the main {@link Selector}. *

* Super-classes can implement this method to react to the event. * * @param count event count. * @throws IOReactorException in case if a non-recoverable I/O error. */ protected abstract void processEvents(int count) throws IOReactorException; /** * Triggered to cancel pending session requests. *

* Super-classes can implement this method to react to the event. * * @throws IOReactorException in case if a non-recoverable I/O error. */ protected abstract void cancelRequests() throws IOReactorException; /** * Activates the main I/O reactor as well as all worker I/O reactors. * The I/O main reactor will start reacting to I/O events and triggering * notification methods. The worker I/O reactor in their turn will start * reacting to I/O events and dispatch I/O event notifications to the given * {@link IOEventDispatch} interface. *

* This method will enter the infinite I/O select loop on * the {@link Selector} instance associated with this I/O reactor and used * to manage creation of new I/O channels. Once a new I/O channel has been * created the processing of I/O events on that channel will be delegated * to one of the worker I/O reactors. *

* The method will remain blocked unto the I/O reactor is shut down or the * execution thread is interrupted. * * @see #processEvents(int) * @see #cancelRequests() * * @throws InterruptedIOException if the dispatch thread is interrupted. * @throws IOReactorException in case if a non-recoverable I/O error. */ @Override public void execute( final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException { Args.notNull(eventDispatch, "Event dispatcher"); synchronized (this.statusLock) { if (this.status.compareTo(IOReactorStatus.SHUTDOWN_REQUEST) >= 0) { this.status = IOReactorStatus.SHUT_DOWN; this.statusLock.notifyAll(); return; } Asserts.check(this.status.compareTo(IOReactorStatus.INACTIVE) == 0, "Illegal state %s", this.status); this.status = IOReactorStatus.ACTIVE; // Start I/O dispatchers for (int i = 0; i < this.dispatchers.length; i++) { final BaseIOReactor dispatcher = new BaseIOReactor(this.selectTimeout, this.interestOpsQueueing); dispatcher.setExceptionHandler(exceptionHandler); this.dispatchers[i] = dispatcher; } for (int i = 0; i < this.workerCount; i++) { final BaseIOReactor dispatcher = this.dispatchers[i]; this.workers[i] = new Worker(dispatcher, eventDispatch); this.threads[i] = this.threadFactory.newThread(this.workers[i]); } } try { for (int i = 0; i < this.workerCount; i++) { if (this.status != IOReactorStatus.ACTIVE) { return; } this.threads[i].start(); } for (;;) { final int readyCount; try { readyCount = this.selector.select(this.selectTimeout); } catch (final InterruptedIOException ex) { throw ex; } catch (final IOException ex) { throw new IOReactorException("Unexpected selector failure", ex); } if (this.status.compareTo(IOReactorStatus.ACTIVE) == 0) { processEvents(readyCount); } // Verify I/O dispatchers for (int i = 0; i < this.workerCount; i++) { final Worker worker = this.workers[i]; final Exception ex = worker.getException(); if (ex != null) { throw new IOReactorException( "I/O dispatch worker terminated abnormally", ex); } } if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) { break; } } } catch (final ClosedSelectorException ex) { addExceptionEvent(ex); } catch (final IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } throw ex; } finally { doShutdown(); synchronized (this.statusLock) { this.status = IOReactorStatus.SHUT_DOWN; this.statusLock.notifyAll(); } } } /** * Activates the shutdown sequence for this reactor. This method will cancel * all pending session requests, close out all active I/O channels, * make an attempt to terminate all worker I/O reactors gracefully, * and finally force-terminate those I/O reactors that failed to * terminate after the specified grace period. * * @throws InterruptedIOException if the shutdown sequence has been * interrupted. */ protected void doShutdown() throws InterruptedIOException { synchronized (this.statusLock) { if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) { return; } this.status = IOReactorStatus.SHUTTING_DOWN; } try { cancelRequests(); } catch (final IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } this.selector.wakeup(); // Close out all channels if (this.selector.isOpen()) { for (final SelectionKey key : this.selector.keys()) { try { final Channel channel = key.channel(); if (channel != null) { channel.close(); } } catch (final IOException ex) { addExceptionEvent(ex); } } // Stop dispatching I/O events try { this.selector.close(); } catch (final IOException ex) { addExceptionEvent(ex); } } // Attempt to shut down I/O dispatchers gracefully for (int i = 0; i < this.workerCount; i++) { final BaseIOReactor dispatcher = this.dispatchers[i]; dispatcher.gracefulShutdown(); } final long gracePeriod = this.config.getShutdownGracePeriod(); try { // Force shut down I/O dispatchers if they fail to terminate // in time for (int i = 0; i < this.workerCount; i++) { final BaseIOReactor dispatcher = this.dispatchers[i]; if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) { dispatcher.awaitShutdown(gracePeriod); } if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) { try { dispatcher.hardShutdown(); } catch (final IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } } } // Join worker threads for (int i = 0; i < this.workerCount; i++) { final Thread t = this.threads[i]; if (t != null) { t.join(gracePeriod); } } } catch (final InterruptedException ex) { throw new InterruptedIOException(ex.getMessage()); } } /** * Assigns the given channel entry to one of the worker I/O reactors. * * @param entry the channel entry. */ protected void addChannel(final ChannelEntry entry) { // Distribute new channels among the workers final int i = Math.abs(this.currentWorker++ % this.workerCount); this.dispatchers[i].addChannel(entry); } /** * Registers the given channel with the main {@link Selector}. * * @param channel the channel. * @param ops interest ops. * @return selection key. * @throws ClosedChannelException if the channel has been already closed. */ protected SelectionKey registerChannel( final SelectableChannel channel, final int ops) throws ClosedChannelException { return channel.register(this.selector, ops); } /** * Prepares the given {@link Socket} by resetting some of its properties. * * @param socket the socket * @throws IOException in case of an I/O error. */ protected void prepareSocket(final Socket socket) throws IOException { socket.setTcpNoDelay(this.config.isTcpNoDelay()); socket.setKeepAlive(this.config.isSoKeepalive()); if (this.config.getSoTimeout() > 0) { socket.setSoTimeout(this.config.getSoTimeout()); } if (this.config.getSndBufSize() > 0) { socket.setSendBufferSize(this.config.getSndBufSize()); } if (this.config.getRcvBufSize() > 0) { socket.setReceiveBufferSize(this.config.getRcvBufSize()); } final int linger = this.config.getSoLinger(); if (linger >= 0) { socket.setSoLinger(true, linger); } } /** * Blocks for the given period of time in milliseconds awaiting * the completion of the reactor shutdown. If the value of * {@code timeout} is set to {@code 0} this method blocks * indefinitely. * * @param timeout the maximum wait time. * @throws InterruptedException if interrupted. */ protected void awaitShutdown(final long timeout) throws InterruptedException { synchronized (this.statusLock) { final long deadline = System.currentTimeMillis() + timeout; long remaining = timeout; while (this.status != IOReactorStatus.SHUT_DOWN) { this.statusLock.wait(remaining); if (timeout > 0) { remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { break; } } } } } @Override public void shutdown() throws IOException { shutdown(2000); } @Override public void shutdown(final long waitMs) throws IOException { synchronized (this.statusLock) { if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) { return; } if (this.status.compareTo(IOReactorStatus.INACTIVE) == 0) { this.status = IOReactorStatus.SHUT_DOWN; cancelRequests(); this.selector.close(); return; } this.status = IOReactorStatus.SHUTDOWN_REQUEST; } this.selector.wakeup(); try { awaitShutdown(waitMs); } catch (final InterruptedException ignore) { } } static void closeChannel(final Channel channel) { try { channel.close(); } catch (final IOException ignore) { } } static class Worker implements Runnable { final BaseIOReactor dispatcher; final IOEventDispatch eventDispatch; private volatile Exception exception; public Worker(final BaseIOReactor dispatcher, final IOEventDispatch eventDispatch) { super(); this.dispatcher = dispatcher; this.eventDispatch = eventDispatch; } @Override public void run() { try { this.dispatcher.execute(this.eventDispatch); } catch (final Exception ex) { this.exception = ex; } } public Exception getException() { return this.exception; } } static class DefaultThreadFactory implements ThreadFactory { private final static AtomicLong COUNT = new AtomicLong(1); @Override public Thread newThread(final Runnable r) { return new Thread(r, "I/O dispatcher " + COUNT.getAndIncrement()); } } } ././@LongLink0100644 0000000 0000000 00000000156 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionRequestImpl.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionRequest0100644 0000000 0000000 00000014240 12613456025 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.nio.reactor; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.Channel; import java.nio.channels.SelectionKey; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.util.Args; /** * Default implementation of {@link SessionRequest}. * * @since 4.0 */ @ThreadSafe public class SessionRequestImpl implements SessionRequest { private volatile boolean completed; private volatile SelectionKey key; private final SocketAddress remoteAddress; private final SocketAddress localAddress; private final Object attachment; private final SessionRequestCallback callback; private volatile int connectTimeout; private volatile IOSession session = null; private volatile IOException exception = null; public SessionRequestImpl( final SocketAddress remoteAddress, final SocketAddress localAddress, final Object attachment, final SessionRequestCallback callback) { super(); Args.notNull(remoteAddress, "Remote address"); this.remoteAddress = remoteAddress; this.localAddress = localAddress; this.attachment = attachment; this.callback = callback; this.connectTimeout = 0; } @Override public SocketAddress getRemoteAddress() { return this.remoteAddress; } @Override public SocketAddress getLocalAddress() { return this.localAddress; } @Override public Object getAttachment() { return this.attachment; } @Override public boolean isCompleted() { return this.completed; } protected void setKey(final SelectionKey key) { this.key = key; } @Override public void waitFor() throws InterruptedException { if (this.completed) { return; } synchronized (this) { while (!this.completed) { wait(); } } } @Override public IOSession getSession() { synchronized (this) { return this.session; } } @Override public IOException getException() { synchronized (this) { return this.exception; } } public void completed(final IOSession session) { Args.notNull(session, "Session"); if (this.completed) { return; } this.completed = true; synchronized (this) { this.session = session; if (this.callback != null) { this.callback.completed(this); } notifyAll(); } } public void failed(final IOException exception) { if (exception == null) { return; } if (this.completed) { return; } this.completed = true; final SelectionKey key = this.key; if (key != null) { key.cancel(); final Channel channel = key.channel(); try { channel.close(); } catch (final IOException ignore) {} } synchronized (this) { this.exception = exception; if (this.callback != null) { this.callback.failed(this); } notifyAll(); } } public void timeout() { if (this.completed) { return; } this.completed = true; final SelectionKey key = this.key; if (key != null) { key.cancel(); final Channel channel = key.channel(); if (channel.isOpen()) { try { channel.close(); } catch (final IOException ignore) {} } } synchronized (this) { if (this.callback != null) { this.callback.timeout(this); } } } @Override public int getConnectTimeout() { return this.connectTimeout; } @Override public void setConnectTimeout(final int timeout) { if (this.connectTimeout != timeout) { this.connectTimeout = timeout; final SelectionKey key = this.key; if (key != null) { key.selector().wakeup(); } } } @Override public void cancel() { if (this.completed) { return; } this.completed = true; final SelectionKey key = this.key; if (key != null) { key.cancel(); final Channel channel = key.channel(); if (channel.isOpen()) { try { channel.close(); } catch (final IOException ignore) {} } } synchronized (this) { if (this.callback != null) { this.callback.cancelled(this); } notifyAll(); } } } ././@LongLink0100644 0000000 0000000 00000000150 12613460517 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/package-info.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/package-info.j0100644 0000000 0000000 00000002456 12613456025 032222 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists 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 implementation of event driven network communication APIs * based on Java NIO. */ package org.apache.http.impl.nio.reactor; ././@LongLink0100644 0000000 0000000 00000000152 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ExceptionEvent.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ExceptionEvent0100644 0000000 0000000 00000004233 12613456025 032401 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.util.Date; import org.apache.http.annotation.Immutable; /** * A {@link Throwable} instance along with a time stamp. * * @since 4.0 */ @Immutable public class ExceptionEvent { private final Throwable ex; private final long time; public ExceptionEvent(final Throwable ex, final Date timestamp) { super(); this.ex = ex; if (timestamp != null) { this.time = timestamp.getTime(); } else { this.time = 0; } } public ExceptionEvent(final Exception ex) { this(ex, new Date()); } public Throwable getCause() { return ex; } public Date getTimestamp() { return new Date(this.time); } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append(new Date(this.time)); buffer.append(" "); buffer.append(this.ex); return buffer.toString(); } } ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionClosedCallback.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionClosedC0100644 0000000 0000000 00000002672 12613456025 032326 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import org.apache.http.nio.reactor.IOSession; /** * Session callback interface used internally by I/O reactor implementations. * * @since 4.0 */ public interface SessionClosedCallback { void sessionClosed(IOSession session); } ././@LongLink0100644 0000000 0000000 00000000150 12613460517 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ChannelEntry.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ChannelEntry.j0100644 0000000 0000000 00000006362 12613456025 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.impl.nio.reactor; import java.nio.channels.SocketChannel; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * {@link SocketChannel} entry maintained by the I/O reactor. If the channel * represents an outgoing client connection, this entry also contains the * original {@link SessionRequestImpl} used to request it. * * @since 4.0 */ @Immutable public class ChannelEntry { private final SocketChannel channel; private final SessionRequestImpl sessionRequest; /** * Creates new ChannelEntry. * * @param channel the channel * @param sessionRequest original session request. Can be {@code null} * if the channel represents an incoming server-side connection. */ public ChannelEntry(final SocketChannel channel, final SessionRequestImpl sessionRequest) { super(); Args.notNull(channel, "Socket channel"); this.channel = channel; this.sessionRequest = sessionRequest; } /** * Creates new ChannelEntry. * * @param channel the channel. */ public ChannelEntry(final SocketChannel channel) { this(channel, null); } /** * Returns the original session request, if available. If the channel * entry represents an incoming server-side connection, returns * {@code null}. * * @return the original session request, if client-side channel, * {@code null} otherwise. */ public SessionRequestImpl getSessionRequest() { return this.sessionRequest; } /** * Returns the original session request attachment, if available. * * @return the original session request attachment, if available, * {@code null} otherwise. */ public Object getAttachment() { if (this.sessionRequest != null) { return this.sessionRequest.getAttachment(); } else { return null; } } /** * Returns the channel. * * @return the channel. */ public SocketChannel getChannel() { return this.channel; } } ././@LongLink0100644 0000000 0000000 00000000165 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/DefaultListeningIOReactor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/DefaultListeni0100644 0000000 0000000 00000026530 12613456025 032361 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.IOException; import java.net.ServerSocket; import java.net.SocketAddress; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ThreadFactory; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.HttpParams; import org.apache.http.util.Asserts; /** * Default implementation of {@link ListeningIOReactor}. This class extends * {@link AbstractMultiworkerIOReactor} with capability to listen for incoming * connections. * * @since 4.0 */ @SuppressWarnings("deprecation") @ThreadSafe // public methods only public class DefaultListeningIOReactor extends AbstractMultiworkerIOReactor implements ListeningIOReactor { private final Queue requestQueue; private final Set endpoints; private final Set pausedEndpoints; private volatile boolean paused; /** * Creates an instance of DefaultListeningIOReactor with the given configuration. * * @param config I/O reactor configuration. * @param threadFactory the factory to create threads. * Can be {@code null}. * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.2 */ public DefaultListeningIOReactor( final IOReactorConfig config, final ThreadFactory threadFactory) throws IOReactorException { super(config, threadFactory); this.requestQueue = new ConcurrentLinkedQueue(); this.endpoints = Collections.synchronizedSet(new HashSet()); this.pausedEndpoints = new HashSet(); } /** * Creates an instance of DefaultListeningIOReactor with the given configuration. * * @param config I/O reactor configuration. * Can be {@code null}. * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.2 */ public DefaultListeningIOReactor(final IOReactorConfig config) throws IOReactorException { this(config, null); } /** * Creates an instance of DefaultListeningIOReactor with default configuration. * * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.2 */ public DefaultListeningIOReactor() throws IOReactorException { this(null, null); } /** * @deprecated (4.2) use {@link DefaultListeningIOReactor#DefaultListeningIOReactor(IOReactorConfig, ThreadFactory)} */ @Deprecated public DefaultListeningIOReactor( final int workerCount, final ThreadFactory threadFactory, final HttpParams params) throws IOReactorException { this(convert(workerCount, params), threadFactory); } /** * @deprecated (4.2) use {@link DefaultListeningIOReactor#DefaultListeningIOReactor(IOReactorConfig)} */ @Deprecated public DefaultListeningIOReactor( final int workerCount, final HttpParams params) throws IOReactorException { this(convert(workerCount, params), null); } @Override protected void cancelRequests() throws IOReactorException { ListenerEndpointImpl request; while ((request = this.requestQueue.poll()) != null) { request.cancel(); } } @Override protected void processEvents(final int readyCount) throws IOReactorException { if (!this.paused) { processSessionRequests(); } if (readyCount > 0) { final Set selectedKeys = this.selector.selectedKeys(); for (final SelectionKey key : selectedKeys) { processEvent(key); } selectedKeys.clear(); } } private void processEvent(final SelectionKey key) throws IOReactorException { try { if (key.isAcceptable()) { final ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); for (;;) { SocketChannel socketChannel = null; try { socketChannel = serverChannel.accept(); } catch (final IOException ex) { if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) { throw new IOReactorException( "Failure accepting connection", ex); } } if (socketChannel == null) { break; } try { prepareSocket(socketChannel.socket()); } catch (final IOException ex) { if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) { throw new IOReactorException( "Failure initalizing socket", ex); } } final ChannelEntry entry = new ChannelEntry(socketChannel); addChannel(entry); } } } catch (final CancelledKeyException ex) { final ListenerEndpoint endpoint = (ListenerEndpoint) key.attachment(); this.endpoints.remove(endpoint); key.attach(null); } } private ListenerEndpointImpl createEndpoint(final SocketAddress address) { return new ListenerEndpointImpl( address, new ListenerEndpointClosedCallback() { @Override public void endpointClosed(final ListenerEndpoint endpoint) { endpoints.remove(endpoint); } }); } @Override public ListenerEndpoint listen(final SocketAddress address) { Asserts.check(this.status.compareTo(IOReactorStatus.ACTIVE) <= 0, "I/O reactor has been shut down"); final ListenerEndpointImpl request = createEndpoint(address); this.requestQueue.add(request); this.selector.wakeup(); return request; } private void processSessionRequests() throws IOReactorException { ListenerEndpointImpl request; while ((request = this.requestQueue.poll()) != null) { final SocketAddress address = request.getAddress(); final ServerSocketChannel serverChannel; try { serverChannel = ServerSocketChannel.open(); } catch (final IOException ex) { throw new IOReactorException("Failure opening server socket", ex); } try { final ServerSocket socket = serverChannel.socket(); socket.setReuseAddress(this.config.isSoReuseAddress()); if (this.config.getSoTimeout() > 0) { socket.setSoTimeout(this.config.getSoTimeout()); } if (this.config.getRcvBufSize() > 0) { socket.setReceiveBufferSize(this.config.getRcvBufSize()); } serverChannel.configureBlocking(false); socket.bind(address, this.config.getBacklogSize()); } catch (final IOException ex) { closeChannel(serverChannel); request.failed(ex); if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) { throw new IOReactorException("Failure binding socket to address " + address, ex); } else { return; } } try { final SelectionKey key = serverChannel.register(this.selector, SelectionKey.OP_ACCEPT); key.attach(request); request.setKey(key); } catch (final IOException ex) { closeChannel(serverChannel); throw new IOReactorException("Failure registering channel " + "with the selector", ex); } this.endpoints.add(request); request.completed(serverChannel.socket().getLocalSocketAddress()); } } @Override public Set getEndpoints() { final Set set = new HashSet(); synchronized (this.endpoints) { final Iterator it = this.endpoints.iterator(); while (it.hasNext()) { final ListenerEndpoint endpoint = it.next(); if (!endpoint.isClosed()) { set.add(endpoint); } else { it.remove(); } } } return set; } @Override public void pause() throws IOException { if (this.paused) { return; } this.paused = true; synchronized (this.endpoints) { for (final ListenerEndpointImpl endpoint : this.endpoints) { if (!endpoint.isClosed()) { endpoint.close(); this.pausedEndpoints.add(endpoint.getAddress()); } } this.endpoints.clear(); } } @Override public void resume() throws IOException { if (!this.paused) { return; } this.paused = false; for (final SocketAddress address: this.pausedEndpoints) { final ListenerEndpointImpl request = createEndpoint(address); this.requestQueue.add(request); } this.pausedEndpoints.clear(); this.selector.wakeup(); } } ././@LongLink0100644 0000000 0000000 00000000163 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionOutputBufferImpl.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionOutputB0100644 0000000 0000000 00000024550 12613456025 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.nio.reactor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.ExpandableBuffer; import org.apache.http.nio.util.HeapByteBufferAllocator; 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.CharArrayBuffer; import org.apache.http.util.CharsetUtils; /** * Default implementation of {@link SessionOutputBuffer} based on * the {@link ExpandableBuffer} class. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public class SessionOutputBufferImpl extends ExpandableBuffer implements SessionOutputBuffer { private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF}; private final CharsetEncoder charencoder; private final int lineBuffersize; private CharBuffer charbuffer; /** * Creates SessionOutputBufferImpl instance. * * @param buffersize input buffer size * @param lineBuffersize buffer size for line operations. Has effect only if * {@code charencoder} is not {@code null}. * @param charencoder charencoder to be used for encoding HTTP protocol elements. * If {@code null} simple type cast will be used for char to byte conversion. * @param allocator memory allocator. * If {@code null} {@link HeapByteBufferAllocator#INSTANCE} will be used. * * @since 4.3 */ public SessionOutputBufferImpl( final int buffersize, final int lineBuffersize, final CharsetEncoder charencoder, final ByteBufferAllocator allocator) { super(buffersize, allocator != null ? allocator : HeapByteBufferAllocator.INSTANCE); this.lineBuffersize = Args.positive(lineBuffersize, "Line buffer size"); this.charencoder = charencoder; } /** * @deprecated (4.3) use * {@link SessionOutputBufferImpl#SessionOutputBufferImpl(int, int, CharsetEncoder, * ByteBufferAllocator)} */ @Deprecated public SessionOutputBufferImpl( final int buffersize, final int lineBuffersize, final ByteBufferAllocator allocator, final HttpParams params) { super(buffersize, allocator); this.lineBuffersize = Args.positive(lineBuffersize, "Line buffer size"); final String charsetName = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET); final Charset charset = CharsetUtils.lookup(charsetName); if (charset != null) { this.charencoder = charset.newEncoder(); final CodingErrorAction a1 = (CodingErrorAction) params.getParameter( CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION); this.charencoder.onMalformedInput(a1 != null ? a1 : CodingErrorAction.REPORT); final CodingErrorAction a2 = (CodingErrorAction) params.getParameter( CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION); this.charencoder.onUnmappableCharacter(a2 != null? a2 : CodingErrorAction.REPORT); } else { this.charencoder = null; } } /** * @deprecated (4.3) use * {@link SessionOutputBufferImpl#SessionOutputBufferImpl(int, int, Charset)} */ @Deprecated public SessionOutputBufferImpl( final int buffersize, final int linebuffersize, final HttpParams params) { this(buffersize, linebuffersize, HeapByteBufferAllocator.INSTANCE, params); } /** * @since 4.3 */ public SessionOutputBufferImpl(final int buffersize) { this(buffersize, 256, null, HeapByteBufferAllocator.INSTANCE); } /** * @since 4.3 */ public SessionOutputBufferImpl( final int buffersize, final int linebuffersize, final Charset charset) { this(buffersize, linebuffersize, charset != null ? charset.newEncoder() : null, HeapByteBufferAllocator.INSTANCE); } /** * @since 4.3 */ public SessionOutputBufferImpl( final int buffersize, final int linebuffersize) { this(buffersize, linebuffersize, null, HeapByteBufferAllocator.INSTANCE); } public void reset(final HttpParams params) { clear(); } @Override public int flush(final WritableByteChannel channel) throws IOException { Args.notNull(channel, "Channel"); setOutputMode(); return channel.write(this.buffer); } @Override public void write(final ByteBuffer src) { if (src == null) { return; } setInputMode(); final int requiredCapacity = this.buffer.position() + src.remaining(); ensureCapacity(requiredCapacity); this.buffer.put(src); } @Override public void write(final ReadableByteChannel src) throws IOException { if (src == null) { return; } setInputMode(); src.read(this.buffer); } private void write(final byte[] b) { if (b == null) { return; } setInputMode(); final int off = 0; final int len = b.length; final int requiredCapacity = this.buffer.position() + len; ensureCapacity(requiredCapacity); this.buffer.put(b, off, len); } private void writeCRLF() { write(CRLF); } @Override public void writeLine(final CharArrayBuffer linebuffer) throws CharacterCodingException { if (linebuffer == null) { return; } setInputMode(); // Do not bother if the buffer is empty if (linebuffer.length() > 0 ) { if (this.charencoder == null) { final int requiredCapacity = this.buffer.position() + linebuffer.length(); ensureCapacity(requiredCapacity); if (this.buffer.hasArray()) { final byte[] b = this.buffer.array(); final int len = linebuffer.length(); final int off = this.buffer.position(); for (int i = 0; i < len; i++) { b[off + i] = (byte) linebuffer.charAt(i); } this.buffer.position(off + len); } else { for (int i = 0; i < linebuffer.length(); i++) { this.buffer.put((byte) linebuffer.charAt(i)); } } } else { if (this.charbuffer == null) { this.charbuffer = CharBuffer.allocate(this.lineBuffersize); } this.charencoder.reset(); // transfer the string in small chunks int remaining = linebuffer.length(); int offset = 0; while (remaining > 0) { int l = this.charbuffer.remaining(); boolean eol = false; if (remaining <= l) { l = remaining; // terminate the encoding process eol = true; } this.charbuffer.put(linebuffer.buffer(), offset, l); this.charbuffer.flip(); boolean retry = true; while (retry) { final CoderResult result = this.charencoder.encode(this.charbuffer, this.buffer, eol); if (result.isError()) { result.throwException(); } if (result.isOverflow()) { expand(); } retry = !result.isUnderflow(); } this.charbuffer.compact(); offset += l; remaining -= l; } // flush the encoder boolean retry = true; while (retry) { final CoderResult result = this.charencoder.flush(this.buffer); if (result.isError()) { result.throwException(); } if (result.isOverflow()) { expand(); } retry = !result.isUnderflow(); } } } writeCRLF(); } @Override public void writeLine(final String s) throws IOException { if (s == null) { return; } if (s.length() > 0) { final CharArrayBuffer tmp = new CharArrayBuffer(s.length()); tmp.append(s); writeLine(tmp); } else { write(CRLF); } } } ././@LongLink0100644 0000000 0000000 00000000157 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/InterestOpsCallback.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/InterestOpsCal0100644 0000000 0000000 00000002762 12613456025 032345 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; /** * Callback interface used internally by I/O session implementations to delegate execution * of a {@link java.nio.channels.SelectionKey#interestOps(int)} operation to the I/O reactor. * * @since 4.1 */ interface InterestOpsCallback { void addInterestOps(InterestOpEntry entry); } ././@LongLink0100644 0000000 0000000 00000000153 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/InterestOpEntry.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/InterestOpEntr0100644 0000000 0000000 00000004424 12613456025 032370 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.nio.channels.SelectionKey; import org.apache.http.util.Args; /** * Helper class, representing an entry on an {@link java.nio.channels.SelectionKey#interestOps(int) * interestOps(int)} queue. * * @since 4.1 */ class InterestOpEntry { private final SelectionKey key; private final int eventMask; public InterestOpEntry(final SelectionKey key, final int eventMask) { super(); Args.notNull(key, "Selection key"); this.key = key; this.eventMask = eventMask; } public SelectionKey getSelectionKey() { return this.key; } public int getEventMask() { return this.eventMask; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof InterestOpEntry) { final InterestOpEntry that = (InterestOpEntry) obj; return this.key.equals(that.key); } else { return false; } } @Override public int hashCode() { return this.key.hashCode(); } } ././@LongLink0100644 0000000 0000000 00000000172 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ListenerEndpointClosedCallback.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ListenerEndpoi0100644 0000000 0000000 00000002740 12613456025 032366 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import org.apache.http.nio.reactor.ListenerEndpoint; /** * Listener endpoint callback interface used internally by I/O reactor * implementations. * * @since 4.0 */ public interface ListenerEndpointClosedCallback { void endpointClosed(ListenerEndpoint endpoint); } ././@LongLink0100644 0000000 0000000 00000000151 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/BaseIOReactor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/BaseIOReactor.0100644 0000000 0000000 00000024144 12613456025 032144 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.InterruptedIOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.reactor.EventMask; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.IOSession; import org.apache.http.util.Args; /** * Default implementation of {@link AbstractIOReactor} that serves as a base * for more advanced {@link org.apache.http.nio.reactor.IOReactor} * implementations. This class adds support for the I/O event dispatching * using {@link IOEventDispatch}, management of buffering sessions, and * session timeout handling. * * @since 4.0 */ @ThreadSafe // public methods only public class BaseIOReactor extends AbstractIOReactor { private final long timeoutCheckInterval; private final Set bufferingSessions; private long lastTimeoutCheck; private IOReactorExceptionHandler exceptionHandler = null; private IOEventDispatch eventDispatch = null; /** * Creates new BaseIOReactor instance. * * @param selectTimeout the select timeout. * @throws IOReactorException in case if a non-recoverable I/O error. */ public BaseIOReactor(final long selectTimeout) throws IOReactorException { this(selectTimeout, false); } /** * Creates new BaseIOReactor instance. * * @param selectTimeout the select timeout. * @param interestOpsQueueing Ops queueing flag. * * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.1 */ public BaseIOReactor( final long selectTimeout, final boolean interestOpsQueueing) throws IOReactorException { super(selectTimeout, interestOpsQueueing); this.bufferingSessions = new HashSet(); this.timeoutCheckInterval = selectTimeout; this.lastTimeoutCheck = System.currentTimeMillis(); } /** * Activates the I/O reactor. The I/O reactor will start reacting to I/O * events and dispatch I/O event notifications to the given * {@link IOEventDispatch}. * * @throws InterruptedIOException if the dispatch thread is interrupted. * @throws IOReactorException in case if a non-recoverable I/O error. */ @Override public void execute( final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException { Args.notNull(eventDispatch, "Event dispatcher"); this.eventDispatch = eventDispatch; execute(); } /** * Sets exception handler for this I/O reactor. * * @param exceptionHandler the exception handler. */ public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) { this.exceptionHandler = exceptionHandler; } /** * Handles the given {@link RuntimeException}. This method delegates * handling of the exception to the {@link IOReactorExceptionHandler}, * if available. * * @param ex the runtime exception. */ protected void handleRuntimeException(final RuntimeException ex) { if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) { throw ex; } } /** * This I/O reactor implementation does not react to the * {@link SelectionKey#OP_ACCEPT} event. *

* Super-classes can override this method to react to the event. */ @Override protected void acceptable(final SelectionKey key) { } /** * This I/O reactor implementation does not react to the * {@link SelectionKey#OP_CONNECT} event. *

* Super-classes can override this method to react to the event. */ @Override protected void connectable(final SelectionKey key) { } /** * Processes {@link SelectionKey#OP_READ} event on the given selection key. * This method dispatches the event notification to the * {@link IOEventDispatch#inputReady(IOSession)} method. */ @Override protected void readable(final SelectionKey key) { final IOSession session = getSession(key); try { // Try to gently feed more data to the event dispatcher // if the session input buffer has not been fully exhausted // (the choice of 5 iterations is purely arbitrary) for (int i = 0; i < 5; i++) { this.eventDispatch.inputReady(session); if (!session.hasBufferedInput() || (session.getEventMask() & SelectionKey.OP_READ) == 0) { break; } } if (session.hasBufferedInput()) { this.bufferingSessions.add(session); } } catch (final CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } catch (final RuntimeException ex) { handleRuntimeException(ex); } } /** * Processes {@link SelectionKey#OP_WRITE} event on the given selection key. * This method dispatches the event notification to the * {@link IOEventDispatch#outputReady(IOSession)} method. */ @Override protected void writable(final SelectionKey key) { final IOSession session = getSession(key); try { this.eventDispatch.outputReady(session); } catch (final CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } catch (final RuntimeException ex) { handleRuntimeException(ex); } } /** * Verifies whether any of the sessions associated with the given selection * keys timed out by invoking the {@link #timeoutCheck(SelectionKey, long)} * method. *

* This method will also invoke the * {@link IOEventDispatch#inputReady(IOSession)} method on all sessions * that have buffered input data. */ @Override protected void validate(final Set keys) { final long currentTime = System.currentTimeMillis(); if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) { this.lastTimeoutCheck = currentTime; if (keys != null) { for (final SelectionKey key : keys) { timeoutCheck(key, currentTime); } } } if (!this.bufferingSessions.isEmpty()) { for (final Iterator it = this.bufferingSessions.iterator(); it.hasNext(); ) { final IOSession session = it.next(); if (!session.hasBufferedInput()) { it.remove(); continue; } try { if ((session.getEventMask() & EventMask.READ) > 0) { this.eventDispatch.inputReady(session); if (!session.hasBufferedInput()) { it.remove(); } } } catch (final CancelledKeyException ex) { it.remove(); queueClosedSession(session); } catch (final RuntimeException ex) { handleRuntimeException(ex); } } } } /** * Processes newly created I/O session. This method dispatches the event * notification to the {@link IOEventDispatch#connected(IOSession)} method. */ @Override protected void sessionCreated(final SelectionKey key, final IOSession session) { try { this.eventDispatch.connected(session); } catch (final CancelledKeyException ex) { queueClosedSession(session); } catch (final RuntimeException ex) { handleRuntimeException(ex); } } /** * Processes timed out I/O session. This method dispatches the event * notification to the {@link IOEventDispatch#timeout(IOSession)} method. */ @Override protected void sessionTimedOut(final IOSession session) { try { this.eventDispatch.timeout(session); } catch (final CancelledKeyException ex) { queueClosedSession(session); } catch (final RuntimeException ex) { handleRuntimeException(ex); } } /** * Processes closed I/O session. This method dispatches the event * notification to the {@link IOEventDispatch#disconnected(IOSession)} * method. */ @Override protected void sessionClosed(final IOSession session) { try { this.eventDispatch.disconnected(session); } catch (final CancelledKeyException ex) { // ignore } catch (final RuntimeException ex) { handleRuntimeException(ex); } } } ././@LongLink0100644 0000000 0000000 00000000155 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractIOReactor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractIOReac0100644 0000000 0000000 00000050340 12613456025 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.impl.nio.reactor; import java.io.IOException; import java.io.InterruptedIOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.nio.channels.ClosedSelectorException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Collections; import java.util.HashSet; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.reactor.IOReactor; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.IOSession; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * Generic implementation of {@link IOReactor} that can used as a subclass * for more specialized I/O reactors. It is based on a single {@link Selector} * instance. * * @since 4.0 */ @ThreadSafe // public methods only public abstract class AbstractIOReactor implements IOReactor { private volatile IOReactorStatus status; private final Object statusMutex; private final long selectTimeout; private final boolean interestOpsQueueing; private final Selector selector; private final Set sessions; private final Queue interestOpsQueue; private final Queue closedSessions; private final Queue newChannels; /** * Creates new AbstractIOReactor instance. * * @param selectTimeout the select timeout. * @throws IOReactorException in case if a non-recoverable I/O error. */ public AbstractIOReactor(final long selectTimeout) throws IOReactorException { this(selectTimeout, false); } /** * Creates new AbstractIOReactor instance. * * @param selectTimeout the select timeout. * @param interestOpsQueueing Ops queueing flag. * * @throws IOReactorException in case if a non-recoverable I/O error. * * @since 4.1 */ public AbstractIOReactor(final long selectTimeout, final boolean interestOpsQueueing) throws IOReactorException { super(); Args.positive(selectTimeout, "Select timeout"); this.selectTimeout = selectTimeout; this.interestOpsQueueing = interestOpsQueueing; this.sessions = Collections.synchronizedSet(new HashSet()); this.interestOpsQueue = new ConcurrentLinkedQueue(); this.closedSessions = new ConcurrentLinkedQueue(); this.newChannels = new ConcurrentLinkedQueue(); try { this.selector = Selector.open(); } catch (final IOException ex) { throw new IOReactorException("Failure opening selector", ex); } this.statusMutex = new Object(); this.status = IOReactorStatus.INACTIVE; } /** * Triggered when the key signals {@link SelectionKey#OP_ACCEPT} readiness. *

* Super-classes can implement this method to react to the event. * * @param key the selection key. */ protected abstract void acceptable(SelectionKey key); /** * Triggered when the key signals {@link SelectionKey#OP_CONNECT} readiness. *

* Super-classes can implement this method to react to the event. * * @param key the selection key. */ protected abstract void connectable(SelectionKey key); /** * Triggered when the key signals {@link SelectionKey#OP_READ} readiness. *

* Super-classes can implement this method to react to the event. * * @param key the selection key. */ protected abstract void readable(SelectionKey key); /** * Triggered when the key signals {@link SelectionKey#OP_WRITE} readiness. *

* Super-classes can implement this method to react to the event. * * @param key the selection key. */ protected abstract void writable(SelectionKey key); /** * Triggered to validate keys currently registered with the selector. This * method is called after each I/O select loop. *

* Super-classes can implement this method to run validity checks on * active sessions and include additional processing that needs to be * executed after each I/O select loop. * * @param keys all selection keys registered with the selector. */ protected abstract void validate(Set keys); /** * Triggered when new session has been created. *

* Super-classes can implement this method to react to the event. * * @param key the selection key. * @param session new I/O session. */ protected void sessionCreated(final SelectionKey key, final IOSession session) { } /** * Triggered when a session has been closed. *

* Super-classes can implement this method to react to the event. * * @param session closed I/O session. */ protected void sessionClosed(final IOSession session) { } /** * Triggered when a session has timed out. *

* Super-classes can implement this method to react to the event. * * @param session timed out I/O session. */ protected void sessionTimedOut(final IOSession session) { } /** * Obtains {@link IOSession} instance associated with the given selection * key. * * @param key the selection key. * @return I/O session. */ protected IOSession getSession(final SelectionKey key) { return (IOSession) key.attachment(); } @Override public IOReactorStatus getStatus() { return this.status; } /** * Returns {@code true} if interest Ops queueing is enabled, {@code false} otherwise. * * @since 4.1 */ public boolean getInterestOpsQueueing() { return this.interestOpsQueueing; } /** * Adds new channel entry. The channel will be asynchronously registered * with the selector. * * @param channelEntry the channel entry. */ public void addChannel(final ChannelEntry channelEntry) { Args.notNull(channelEntry, "Channel entry"); this.newChannels.add(channelEntry); this.selector.wakeup(); } /** * Activates the I/O reactor. The I/O reactor will start reacting to * I/O events and triggering notification methods. *

* This method will enter the infinite I/O select loop on * the {@link Selector} instance associated with this I/O reactor. *

* The method will remain blocked unto the I/O reactor is shut down or the * execution thread is interrupted. * * @see #acceptable(SelectionKey) * @see #connectable(SelectionKey) * @see #readable(SelectionKey) * @see #writable(SelectionKey) * @see #timeoutCheck(SelectionKey, long) * @see #validate(Set) * @see #sessionCreated(SelectionKey, IOSession) * @see #sessionClosed(IOSession) * * @throws InterruptedIOException if the dispatch thread is interrupted. * @throws IOReactorException in case if a non-recoverable I/O error. */ protected void execute() throws InterruptedIOException, IOReactorException { this.status = IOReactorStatus.ACTIVE; try { for (;;) { final int readyCount; try { readyCount = this.selector.select(this.selectTimeout); } catch (final InterruptedIOException ex) { throw ex; } catch (final IOException ex) { throw new IOReactorException("Unexpected selector failure", ex); } if (this.status == IOReactorStatus.SHUT_DOWN) { // Hard shut down. Exit select loop immediately break; } if (this.status == IOReactorStatus.SHUTTING_DOWN) { // Graceful shutdown in process // Try to close things out nicely closeSessions(); closeNewChannels(); } // Process selected I/O events if (readyCount > 0) { processEvents(this.selector.selectedKeys()); } // Validate active channels validate(this.selector.keys()); // Process closed sessions processClosedSessions(); // If active process new channels if (this.status == IOReactorStatus.ACTIVE) { processNewChannels(); } // Exit select loop if graceful shutdown has been completed if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0 && this.sessions.isEmpty()) { break; } if (this.interestOpsQueueing) { // process all pending interestOps() operations processPendingInterestOps(); } } } catch (final ClosedSelectorException ignore) { } finally { hardShutdown(); synchronized (this.statusMutex) { this.statusMutex.notifyAll(); } } } private void processEvents(final Set selectedKeys) { for (final SelectionKey key : selectedKeys) { processEvent(key); } selectedKeys.clear(); } /** * Processes new event on the given selection key. * * @param key the selection key that triggered an event. */ protected void processEvent(final SelectionKey key) { final IOSessionImpl session = (IOSessionImpl) key.attachment(); try { if (key.isAcceptable()) { acceptable(key); } if (key.isConnectable()) { connectable(key); } if (key.isReadable()) { session.resetLastRead(); readable(key); } if (key.isWritable()) { session.resetLastWrite(); writable(key); } } catch (final CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } } /** * Queues the given I/O session to be processed asynchronously as closed. * * @param session the closed I/O session. */ protected void queueClosedSession(final IOSession session) { if (session != null) { this.closedSessions.add(session); } } private void processNewChannels() throws IOReactorException { ChannelEntry entry; while ((entry = this.newChannels.poll()) != null) { final SocketChannel channel; final SelectionKey key; try { channel = entry.getChannel(); channel.configureBlocking(false); key = channel.register(this.selector, SelectionKey.OP_READ); } catch (final ClosedChannelException ex) { final SessionRequestImpl sessionRequest = entry.getSessionRequest(); if (sessionRequest != null) { sessionRequest.failed(ex); } return; } catch (final IOException ex) { throw new IOReactorException("Failure registering channel " + "with the selector", ex); } final SessionClosedCallback sessionClosedCallback = new SessionClosedCallback() { @Override public void sessionClosed(final IOSession session) { queueClosedSession(session); } }; InterestOpsCallback interestOpsCallback = null; if (this.interestOpsQueueing) { interestOpsCallback = new InterestOpsCallback() { @Override public void addInterestOps(final InterestOpEntry entry) { queueInterestOps(entry); } }; } final IOSession session; try { session = new IOSessionImpl(key, interestOpsCallback, sessionClosedCallback); int timeout = 0; try { timeout = channel.socket().getSoTimeout(); } catch (final IOException ex) { // Very unlikely to happen and is not fatal // as the protocol layer is expected to overwrite // this value anyways } session.setAttribute(IOSession.ATTACHMENT_KEY, entry.getAttachment()); session.setSocketTimeout(timeout); } catch (final CancelledKeyException ex) { continue; } try { this.sessions.add(session); final SessionRequestImpl sessionRequest = entry.getSessionRequest(); if (sessionRequest != null) { sessionRequest.completed(session); } key.attach(session); sessionCreated(key, session); } catch (final CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } } } private void processClosedSessions() { IOSession session; while ((session = this.closedSessions.poll()) != null) { if (this.sessions.remove(session)) { try { sessionClosed(session); } catch (final CancelledKeyException ex) { // ignore and move on } } } } private void processPendingInterestOps() { // validity check if (!this.interestOpsQueueing) { return; } InterestOpEntry entry; while ((entry = this.interestOpsQueue.poll()) != null) { // obtain the operation's details final SelectionKey key = entry.getSelectionKey(); final int eventMask = entry.getEventMask(); if (key.isValid()) { key.interestOps(eventMask); } } } private boolean queueInterestOps(final InterestOpEntry entry) { // validity checks Asserts.check(this.interestOpsQueueing, "Interest ops queueing not enabled"); if (entry == null) { return false; } // add this operation to the interestOps() queue this.interestOpsQueue.add(entry); return true; } /** * Triggered to verify whether the I/O session associated with the * given selection key has not timed out. *

* Super-classes can implement this method to react to the event. * * @param key the selection key. * @param now current time as long value. */ protected void timeoutCheck(final SelectionKey key, final long now) { final IOSessionImpl session = (IOSessionImpl) key.attachment(); if (session != null) { final int timeout = session.getSocketTimeout(); if (timeout > 0) { if (session.getLastAccessTime() + timeout < now) { sessionTimedOut(session); } } } } /** * Closes out all I/O sessions maintained by this I/O reactor. */ protected void closeSessions() { synchronized (this.sessions) { for (final IOSession session : this.sessions) { session.close(); } } } /** * Closes out all new channels pending registration with the selector of * this I/O reactor. * @throws IOReactorException - not thrown currently */ protected void closeNewChannels() throws IOReactorException { ChannelEntry entry; while ((entry = this.newChannels.poll()) != null) { final SessionRequestImpl sessionRequest = entry.getSessionRequest(); if (sessionRequest != null) { sessionRequest.cancel(); } final SocketChannel channel = entry.getChannel(); try { channel.close(); } catch (final IOException ignore) { } } } /** * Closes out all active channels registered with the selector of * this I/O reactor. * @throws IOReactorException - not thrown currently */ protected void closeActiveChannels() throws IOReactorException { try { final Set keys = this.selector.keys(); for (final SelectionKey key : keys) { final IOSession session = getSession(key); if (session != null) { session.close(); } } this.selector.close(); } catch (final IOException ignore) { } } /** * Attempts graceful shutdown of this I/O reactor. */ public void gracefulShutdown() { synchronized (this.statusMutex) { if (this.status != IOReactorStatus.ACTIVE) { // Already shutting down return; } this.status = IOReactorStatus.SHUTTING_DOWN; } this.selector.wakeup(); } /** * Attempts force-shutdown of this I/O reactor. */ public void hardShutdown() throws IOReactorException { synchronized (this.statusMutex) { if (this.status == IOReactorStatus.SHUT_DOWN) { // Already shut down return; } this.status = IOReactorStatus.SHUT_DOWN; } closeNewChannels(); closeActiveChannels(); processClosedSessions(); } /** * Blocks for the given period of time in milliseconds awaiting * the completion of the reactor shutdown. * * @param timeout the maximum wait time. * @throws InterruptedException if interrupted. */ public void awaitShutdown(final long timeout) throws InterruptedException { synchronized (this.statusMutex) { final long deadline = System.currentTimeMillis() + timeout; long remaining = timeout; while (this.status != IOReactorStatus.SHUT_DOWN) { this.statusMutex.wait(remaining); if (timeout > 0) { remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { break; } } } } } @Override public void shutdown(final long gracePeriod) throws IOReactorException { if (this.status != IOReactorStatus.INACTIVE) { gracefulShutdown(); try { awaitShutdown(gracePeriod); } catch (final InterruptedException ignore) { } } if (this.status != IOReactorStatus.SHUT_DOWN) { hardShutdown(); } } @Override public void shutdown() throws IOReactorException { shutdown(1000); } } ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionRequestHandle.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionRequest0100644 0000000 0000000 00000004054 12613456025 032436 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import org.apache.http.annotation.Immutable; import org.apache.http.util.Args; /** * Session request handle class used by I/O reactor implementations to keep * a reference to a {@link org.apache.http.nio.reactor.SessionRequest} along * with the time the request was made. * * @since 4.0 */ @Immutable public class SessionRequestHandle { private final SessionRequestImpl sessionRequest; private final long requestTime; public SessionRequestHandle(final SessionRequestImpl sessionRequest) { super(); Args.notNull(sessionRequest, "Session request"); this.sessionRequest = sessionRequest; this.requestTime = System.currentTimeMillis(); } public SessionRequestImpl getSessionRequest() { return this.sessionRequest; } public long getRequestTime() { return this.requestTime; } } ././@LongLink0100644 0000000 0000000 00000000162 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionInputBufferImpl.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionInputBu0100644 0000000 0000000 00000033330 12613456025 032373 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import org.apache.http.MessageConstraintException; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.config.MessageConstraints; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.ExpandableBuffer; import org.apache.http.nio.util.HeapByteBufferAllocator; 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.CharArrayBuffer; import org.apache.http.util.CharsetUtils; /** * Default implementation of {@link SessionInputBuffer} based on * the {@link ExpandableBuffer} class. * * @since 4.0 */ @SuppressWarnings("deprecation") @NotThreadSafe public class SessionInputBufferImpl extends ExpandableBuffer implements SessionInputBuffer { private final CharsetDecoder chardecoder; private final MessageConstraints constraints; private final int lineBuffersize; private CharBuffer charbuffer; /** * Creates SessionInputBufferImpl instance. * * @param buffersize input buffer size * @param lineBuffersize buffer size for line operations. Has effect only if * {@code chardecoder} is not {@code null}. * @param chardecoder chardecoder to be used for decoding HTTP protocol elements. * If {@code null} simple type cast will be used for byte to char conversion. * @param constraints Message constraints. If {@code null} * {@link MessageConstraints#DEFAULT} will be used. * @param allocator memory allocator. * If {@code null} {@link HeapByteBufferAllocator#INSTANCE} will be used. * * @since 4.4 */ public SessionInputBufferImpl( final int buffersize, final int lineBuffersize, final MessageConstraints constraints, final CharsetDecoder chardecoder, final ByteBufferAllocator allocator) { super(buffersize, allocator != null ? allocator : HeapByteBufferAllocator.INSTANCE); this.lineBuffersize = Args.positive(lineBuffersize, "Line buffer size"); this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; this.chardecoder = chardecoder; } /** * Creates SessionInputBufferImpl instance. * * @param buffersize input buffer size * @param lineBuffersize buffer size for line operations. Has effect only if * {@code chardecoder} is not {@code null}. * @param chardecoder chardecoder to be used for decoding HTTP protocol elements. * If {@code null} simple type cast will be used for byte to char conversion. * @param allocator memory allocator. * If {@code null} {@link HeapByteBufferAllocator#INSTANCE} will be used. * * @since 4.3 */ public SessionInputBufferImpl( final int buffersize, final int lineBuffersize, final CharsetDecoder chardecoder, final ByteBufferAllocator allocator) { this(buffersize, lineBuffersize, null, chardecoder, allocator); } /** * @deprecated (4.3) use * {@link SessionInputBufferImpl#SessionInputBufferImpl(int, int, CharsetDecoder, * ByteBufferAllocator)} */ @Deprecated public SessionInputBufferImpl( final int buffersize, final int lineBuffersize, final ByteBufferAllocator allocator, final HttpParams params) { super(buffersize, allocator); this.lineBuffersize = Args.positive(lineBuffersize, "Line buffer size"); final String charsetName = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET); final Charset charset = CharsetUtils.lookup(charsetName); if (charset != null) { this.chardecoder = charset.newDecoder(); final CodingErrorAction a1 = (CodingErrorAction) params.getParameter( CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION); this.chardecoder.onMalformedInput(a1 != null ? a1 : CodingErrorAction.REPORT); final CodingErrorAction a2 = (CodingErrorAction) params.getParameter( CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION); this.chardecoder.onUnmappableCharacter(a2 != null? a2 : CodingErrorAction.REPORT); } else { this.chardecoder = null; } this.constraints = MessageConstraints.DEFAULT; } /** * @deprecated (4.3) use * {@link SessionInputBufferImpl#SessionInputBufferImpl(int, int, Charset)} */ @Deprecated public SessionInputBufferImpl( final int buffersize, final int linebuffersize, final HttpParams params) { this(buffersize, linebuffersize, HeapByteBufferAllocator.INSTANCE, params); } /** * @since 4.3 */ public SessionInputBufferImpl( final int buffersize, final int lineBuffersize, final Charset charset) { this(buffersize, lineBuffersize, null, charset != null ? charset.newDecoder() : null, HeapByteBufferAllocator.INSTANCE); } /** * @since 4.3 */ public SessionInputBufferImpl( final int buffersize, final int lineBuffersize, final MessageConstraints constraints, final Charset charset) { this(buffersize, lineBuffersize, constraints, charset != null ? charset.newDecoder() : null, HeapByteBufferAllocator.INSTANCE); } /** * @since 4.3 */ public SessionInputBufferImpl( final int buffersize, final int lineBuffersize) { this(buffersize, lineBuffersize, null, null, HeapByteBufferAllocator.INSTANCE); } /** * @since 4.3 */ public SessionInputBufferImpl(final int buffersize) { this(buffersize, 256, null, null, HeapByteBufferAllocator.INSTANCE); } @Override public int fill(final ReadableByteChannel channel) throws IOException { Args.notNull(channel, "Channel"); setInputMode(); if (!this.buffer.hasRemaining()) { expand(); } return channel.read(this.buffer); } @Override public int read() { setOutputMode(); return this.buffer.get() & 0xff; } @Override public int read(final ByteBuffer dst, final int maxLen) { if (dst == null) { return 0; } setOutputMode(); final int len = Math.min(dst.remaining(), maxLen); final int chunk = Math.min(this.buffer.remaining(), len); if (this.buffer.remaining() > chunk) { final int oldLimit = this.buffer.limit(); final int newLimit = this.buffer.position() + chunk; this.buffer.limit(newLimit); dst.put(this.buffer); this.buffer.limit(oldLimit); return len; } else { dst.put(this.buffer); } return chunk; } @Override public int read(final ByteBuffer dst) { if (dst == null) { return 0; } return read(dst, dst.remaining()); } @Override public int read(final WritableByteChannel dst, final int maxLen) throws IOException { if (dst == null) { return 0; } setOutputMode(); final int bytesRead; if (this.buffer.remaining() > maxLen) { final int oldLimit = this.buffer.limit(); final int newLimit = oldLimit - (this.buffer.remaining() - maxLen); this.buffer.limit(newLimit); bytesRead = dst.write(this.buffer); this.buffer.limit(oldLimit); } else { bytesRead = dst.write(this.buffer); } return bytesRead; } @Override public int read(final WritableByteChannel dst) throws IOException { if (dst == null) { return 0; } setOutputMode(); return dst.write(this.buffer); } @Override public boolean readLine( final CharArrayBuffer linebuffer, final boolean endOfStream) throws CharacterCodingException { setOutputMode(); // See if there is LF char present in the buffer int pos = -1; for (int i = this.buffer.position(); i < this.buffer.limit(); i++) { final int b = this.buffer.get(i); if (b == HTTP.LF) { pos = i + 1; break; } } final int maxLineLen = this.constraints.getMaxLineLength(); if (maxLineLen > 0) { final int currentLen = (pos > 0 ? pos : this.buffer.limit()) - this.buffer.position(); if (currentLen >= maxLineLen) { throw new MessageConstraintException("Maximum line length limit exceeded"); } } if (pos == -1) { if (endOfStream && this.buffer.hasRemaining()) { // No more data. Get the rest pos = this.buffer.limit(); } else { // Either no complete line present in the buffer // or no more data is expected return false; } } final int origLimit = this.buffer.limit(); this.buffer.limit(pos); final int requiredCapacity = this.buffer.limit() - this.buffer.position(); // Ensure capacity of len assuming ASCII as the most likely charset linebuffer.ensureCapacity(requiredCapacity); if (this.chardecoder == null) { if (this.buffer.hasArray()) { final byte[] b = this.buffer.array(); final int off = this.buffer.position(); final int len = this.buffer.remaining(); linebuffer.append(b, off, len); this.buffer.position(off + len); } else { while (this.buffer.hasRemaining()) { linebuffer.append((char) (this.buffer.get() & 0xff)); } } } else { if (this.charbuffer == null) { this.charbuffer = CharBuffer.allocate(this.lineBuffersize); } this.chardecoder.reset(); for (;;) { final CoderResult result = this.chardecoder.decode( this.buffer, this.charbuffer, true); if (result.isError()) { result.throwException(); } if (result.isOverflow()) { this.charbuffer.flip(); linebuffer.append( this.charbuffer.array(), this.charbuffer.position(), this.charbuffer.remaining()); this.charbuffer.clear(); } if (result.isUnderflow()) { break; } } // flush the decoder this.chardecoder.flush(this.charbuffer); this.charbuffer.flip(); // append the decoded content to the line buffer if (this.charbuffer.hasRemaining()) { linebuffer.append( this.charbuffer.array(), this.charbuffer.position(), this.charbuffer.remaining()); } } this.buffer.limit(origLimit); // discard LF if found int l = linebuffer.length(); if (l > 0) { if (linebuffer.charAt(l - 1) == HTTP.LF) { l--; linebuffer.setLength(l); } // discard CR if found if (l > 0) { if (linebuffer.charAt(l - 1) == HTTP.CR) { l--; linebuffer.setLength(l); } } } return true; } @Override public String readLine(final boolean endOfStream) throws CharacterCodingException { final CharArrayBuffer buffer = new CharArrayBuffer(64); final boolean found = readLine(buffer, endOfStream); if (found) { return buffer.toString(); } else { return null; } } } ././@LongLink0100644 0000000 0000000 00000000156 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractIODispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractIODisp0100644 0000000 0000000 00000015050 12613456025 032253 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.io.IOException; import org.apache.http.annotation.Immutable; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.ssl.SSLIOSession; import org.apache.http.util.Asserts; /** * Abstract {@link IOEventDispatch} implementation that supports both plain (non-encrypted) * and SSL encrypted HTTP connections. * * @param the connection type. * @since 4.2 */ @Immutable // provided injected dependencies are immutable public abstract class AbstractIODispatch implements IOEventDispatch { protected abstract T createConnection(IOSession session); protected abstract void onConnected(T conn); protected abstract void onClosed(T conn); protected abstract void onException(T conn, IOException ex); protected abstract void onInputReady(T conn); protected abstract void onOutputReady(T conn); protected abstract void onTimeout(T conn); private void ensureNotNull(final T conn) { Asserts.notNull(conn, "HTTP connection"); } @Override public void connected(final IOSession session) { @SuppressWarnings("unchecked") T conn = (T) session.getAttribute(IOEventDispatch.CONNECTION_KEY); try { if (conn == null) { conn = createConnection(session); session.setAttribute(IOEventDispatch.CONNECTION_KEY, conn); } onConnected(conn); final SSLIOSession ssliosession = (SSLIOSession) session.getAttribute( SSLIOSession.SESSION_KEY); if (ssliosession != null) { try { synchronized (ssliosession) { if (!ssliosession.isInitialized()) { ssliosession.initialize(); } } } catch (final IOException ex) { onException(conn, ex); ssliosession.shutdown(); } } } catch (final RuntimeException ex) { session.shutdown(); throw ex; } } @Override public void disconnected(final IOSession session) { @SuppressWarnings("unchecked") final T conn = (T) session.getAttribute(IOEventDispatch.CONNECTION_KEY); if (conn != null) { onClosed(conn); } } @Override public void inputReady(final IOSession session) { @SuppressWarnings("unchecked") final T conn = (T) session.getAttribute(IOEventDispatch.CONNECTION_KEY); try { ensureNotNull(conn); final SSLIOSession ssliosession = (SSLIOSession) session.getAttribute( SSLIOSession.SESSION_KEY); if (ssliosession == null) { onInputReady(conn); } else { try { if (!ssliosession.isInitialized()) { ssliosession.initialize(); } if (ssliosession.isAppInputReady()) { onInputReady(conn); } ssliosession.inboundTransport(); } catch (final IOException ex) { onException(conn, ex); ssliosession.shutdown(); } } } catch (final RuntimeException ex) { session.shutdown(); throw ex; } } @Override public void outputReady(final IOSession session) { @SuppressWarnings("unchecked") final T conn = (T) session.getAttribute(IOEventDispatch.CONNECTION_KEY); try { ensureNotNull(conn); final SSLIOSession ssliosession = (SSLIOSession) session.getAttribute( SSLIOSession.SESSION_KEY); if (ssliosession == null) { onOutputReady(conn); } else { try { if (!ssliosession.isInitialized()) { ssliosession.initialize(); } if (ssliosession.isAppOutputReady()) { onOutputReady(conn); } ssliosession.outboundTransport(); } catch (final IOException ex) { onException(conn, ex); ssliosession.shutdown(); } } } catch (final RuntimeException ex) { session.shutdown(); throw ex; } } @Override public void timeout(final IOSession session) { @SuppressWarnings("unchecked") final T conn = (T) session.getAttribute(IOEventDispatch.CONNECTION_KEY); try { final SSLIOSession ssliosession = (SSLIOSession) session.getAttribute( SSLIOSession.SESSION_KEY); ensureNotNull(conn); onTimeout(conn); if (ssliosession != null) { synchronized (ssliosession) { if (ssliosession.isOutboundDone() && !ssliosession.isInboundDone()) { // The session failed to terminate cleanly ssliosession.shutdown(); } } } } catch (final RuntimeException ex) { session.shutdown(); throw ex; } } } ././@LongLink0100644 0000000 0000000 00000000153 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/IOReactorConfig.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/IOReactorConfi0100644 0000000 0000000 00000036635 12613456025 032262 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.util.Args; /** * I/O reactor configuration parameters. * * @since 4.2 */ @NotThreadSafe public final class IOReactorConfig implements Cloneable { private static final int AVAIL_PROCS = Runtime.getRuntime().availableProcessors(); public static final IOReactorConfig DEFAULT = new Builder().build(); // TODO: make final private long selectInterval; private long shutdownGracePeriod; private boolean interestOpQueued; private int ioThreadCount; private int soTimeout; private boolean soReuseAddress; private int soLinger; private boolean soKeepAlive; private boolean tcpNoDelay; private int connectTimeout; private int sndBufSize; private int rcvBufSize; private int backlogSize; @Deprecated public IOReactorConfig() { super(); this.selectInterval = 1000; this.shutdownGracePeriod = 500; this.interestOpQueued = false; this.ioThreadCount = AVAIL_PROCS; this.soTimeout = 0; this.soReuseAddress = false; this.soLinger = -1; this.soKeepAlive = false; this.tcpNoDelay = true; this.connectTimeout = 0; this.sndBufSize = 0; this.rcvBufSize = 0; this.backlogSize = 0; } IOReactorConfig( final long selectInterval, final long shutdownGracePeriod, final boolean interestOpQueued, final int ioThreadCount, final int soTimeout, final boolean soReuseAddress, final int soLinger, final boolean soKeepAlive, final boolean tcpNoDelay, final int connectTimeout, final int sndBufSize, final int rcvBufSize, final int backlogSize) { super(); this.selectInterval = selectInterval; this.shutdownGracePeriod = shutdownGracePeriod; this.interestOpQueued = interestOpQueued; this.ioThreadCount = ioThreadCount; this.soTimeout = soTimeout; this.soReuseAddress = soReuseAddress; this.soLinger = soLinger; this.soKeepAlive = soKeepAlive; this.tcpNoDelay = tcpNoDelay; this.connectTimeout = connectTimeout; this.sndBufSize = sndBufSize; this.rcvBufSize = rcvBufSize; this.backlogSize = backlogSize; } /** * Determines time interval in milliseconds at which the I/O reactor wakes up to check for * timed out sessions and session requests. *

* Default: {@code 1000} milliseconds. */ public long getSelectInterval() { return this.selectInterval; } /** * @deprecated (4.3) use {@link Builder#setSelectInterval(long)} */ @Deprecated public void setSelectInterval(final long selectInterval) { Args.positive(selectInterval, "Select internal"); this.selectInterval = selectInterval; } /** * Determines grace period in milliseconds the I/O reactors are expected to block waiting * for individual worker threads to terminate cleanly. *

* Default: {@code 500} milliseconds. */ public long getShutdownGracePeriod() { return this.shutdownGracePeriod; } /** * @deprecated (4.3) use {@link Builder#setShutdownGracePeriod(long)} */ @Deprecated public void setShutdownGracePeriod(final long gracePeriod) { Args.positive(gracePeriod, "Shutdown grace period"); this.shutdownGracePeriod = gracePeriod; } /** * Determines whether or not I/O interest operations are to be queued and executed * asynchronously by the I/O reactor thread or to be applied to the underlying * {@link java.nio.channels.SelectionKey} immediately. *

* Default: {@code false} * * @see java.nio.channels.SelectionKey * @see java.nio.channels.SelectionKey#interestOps() * @see java.nio.channels.SelectionKey#interestOps(int) */ public boolean isInterestOpQueued() { return this.interestOpQueued; } /** * @deprecated (4.3) use {@link Builder#setInterestOpQueued(boolean)} */ @Deprecated public void setInterestOpQueued(final boolean interestOpQueued) { this.interestOpQueued = interestOpQueued; } /** * Determines the number of I/O dispatch threads to be used by the I/O reactor. *

* Default: {@code 2} */ public int getIoThreadCount() { return this.ioThreadCount; } /** * @deprecated (4.3) use {@link Builder#setIoThreadCount(int)} */ @Deprecated public void setIoThreadCount(final int ioThreadCount) { Args.positive(ioThreadCount, "I/O thread count"); this.ioThreadCount = ioThreadCount; } /** * Determines the default socket timeout value for non-blocking I/O operations. *

* Default: {@code 0} (no timeout) * * @see java.net.SocketOptions#SO_TIMEOUT */ public int getSoTimeout() { return soTimeout; } /** * @deprecated (4.3) use {@link Builder#setSoTimeout(int)} */ @Deprecated public void setSoTimeout(final int soTimeout) { this.soTimeout = soTimeout; } /** * Determines the default value of the {@link java.net.SocketOptions#SO_REUSEADDR} parameter * for newly created sockets. *

* Default: {@code false} * * @see java.net.SocketOptions#SO_REUSEADDR */ public boolean isSoReuseAddress() { return soReuseAddress; } /** * @deprecated (4.3) use {@link Builder#setSoReuseAddress(boolean)} */ @Deprecated public void setSoReuseAddress(final boolean soReuseAddress) { this.soReuseAddress = soReuseAddress; } /** * Determines the default value of the {@link java.net.SocketOptions#SO_LINGER} parameter * for newly created sockets. *

* Default: {@code -1} * * @see java.net.SocketOptions#SO_LINGER */ public int getSoLinger() { return soLinger; } /** * @deprecated (4.3) use {@link Builder#setSoLinger(int)} */ @Deprecated public void setSoLinger(final int soLinger) { this.soLinger = soLinger; } /** * Determines the default value of the {@link java.net.SocketOptions#SO_KEEPALIVE} parameter * for newly created sockets. *

* Default: {@code -1} * * @see java.net.SocketOptions#SO_KEEPALIVE */ public boolean isSoKeepalive() { return this.soKeepAlive; } /** * @deprecated (4.3) use {@link Builder#setSoKeepAlive(boolean)} */ @Deprecated public void setSoKeepalive(final boolean soKeepAlive) { this.soKeepAlive = soKeepAlive; } /** * Determines the default value of the {@link java.net.SocketOptions#TCP_NODELAY} parameter * for newly created sockets. *

* Default: {@code false} * * @see java.net.SocketOptions#TCP_NODELAY */ public boolean isTcpNoDelay() { return tcpNoDelay; } /** * @deprecated (4.3) use {@link Builder#setTcpNoDelay(boolean)} */ @Deprecated public void setTcpNoDelay(final boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } /** * Determines the default connect timeout value for non-blocking connection requests. *

* Default: {@code 0} (no timeout) */ public int getConnectTimeout() { return connectTimeout; } /** * @deprecated (4.3) use {@link Builder#setConnectTimeout(int)} */ @Deprecated public void setConnectTimeout(final int connectTimeout) { this.connectTimeout = connectTimeout; } /** * Determines the default value of the {@link java.net.SocketOptions#SO_SNDBUF} parameter * for newly created sockets. *

* Default: {@code 0} (system default) * * @see java.net.SocketOptions#SO_SNDBUF */ public int getSndBufSize() { return sndBufSize; } /** * @deprecated (4.3) use {@link Builder#setSndBufSize(int)} */ @Deprecated public void setSndBufSize(final int sndBufSize) { this.sndBufSize = sndBufSize; } /** * Determines the default value of the {@link java.net.SocketOptions#SO_RCVBUF} parameter * for newly created sockets. *

* Default: {@code 0} (system default) * * @see java.net.SocketOptions#SO_RCVBUF */ public int getRcvBufSize() { return rcvBufSize; } /** * @deprecated (4.3) use {@link Builder#setRcvBufSize(int)} */ @Deprecated public void setRcvBufSize(final int rcvBufSize) { this.rcvBufSize = rcvBufSize; } /** * Determines the default backlog size value for server sockets binds. *

* Default: {@code 0} (system default) * * @since 4.4 */ public int getBacklogSize() { return backlogSize; } @Override protected IOReactorConfig clone() throws CloneNotSupportedException { return (IOReactorConfig) super.clone(); } public static Builder custom() { return new Builder(); } public static Builder copy(final IOReactorConfig config) { Args.notNull(config, "I/O reactor config"); return new Builder() .setSelectInterval(config.getSelectInterval()) .setShutdownGracePeriod(config.getShutdownGracePeriod()) .setInterestOpQueued(config.isInterestOpQueued()) .setIoThreadCount(config.getIoThreadCount()) .setSoTimeout(config.getSoTimeout()) .setSoReuseAddress(config.isSoReuseAddress()) .setSoLinger(config.getSoLinger()) .setSoKeepAlive(config.isSoKeepalive()) .setTcpNoDelay(config.isTcpNoDelay()) .setConnectTimeout(config.getConnectTimeout()) .setSndBufSize(config.getSndBufSize()) .setRcvBufSize(config.getRcvBufSize()) .setBacklogSize(config.getBacklogSize()); } public static class Builder { private long selectInterval; private long shutdownGracePeriod; private boolean interestOpQueued; private int ioThreadCount; private int soTimeout; private boolean soReuseAddress; private int soLinger; private boolean soKeepAlive; private boolean tcpNoDelay; private int connectTimeout; private int sndBufSize; private int rcvBufSize; private int backlogSize; Builder() { this.selectInterval = 1000; this.shutdownGracePeriod = 500; this.interestOpQueued = false; this.ioThreadCount = AVAIL_PROCS; this.soTimeout = 0; this.soReuseAddress = false; this.soLinger = -1; this.soKeepAlive = false; this.tcpNoDelay = true; this.connectTimeout = 0; this.sndBufSize = 0; this.rcvBufSize = 0; this.backlogSize = 0; } public Builder setSelectInterval(final long selectInterval) { this.selectInterval = selectInterval; return this; } public Builder setShutdownGracePeriod(final long shutdownGracePeriod) { this.shutdownGracePeriod = shutdownGracePeriod; return this; } public Builder setInterestOpQueued(final boolean interestOpQueued) { this.interestOpQueued = interestOpQueued; return this; } public Builder setIoThreadCount(final int ioThreadCount) { this.ioThreadCount = ioThreadCount; return this; } 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 Builder setConnectTimeout(final int connectTimeout) { this.connectTimeout = connectTimeout; return this; } public Builder setSndBufSize(final int sndBufSize) { this.sndBufSize = sndBufSize; return this; } public Builder setRcvBufSize(final int rcvBufSize) { this.rcvBufSize = rcvBufSize; return this; } public Builder setBacklogSize(final int backlogSize) { this.backlogSize = backlogSize; return this; } public IOReactorConfig build() { return new IOReactorConfig( selectInterval, shutdownGracePeriod, interestOpQueued, ioThreadCount, soTimeout, soReuseAddress, soLinger, soKeepAlive, tcpNoDelay, connectTimeout, sndBufSize, rcvBufSize, backlogSize); } } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[selectInterval=").append(this.selectInterval) .append(", shutdownGracePeriod=").append(this.shutdownGracePeriod) .append(", interestOpQueued=").append(this.interestOpQueued) .append(", ioThreadCount=").append(this.ioThreadCount) .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(", connectTimeout=").append(this.connectTimeout) .append(", sndBufSize=").append(this.sndBufSize) .append(", rcvBufSize=").append(this.rcvBufSize) .append(", backlogSize=").append(this.backlogSize) .append("]"); return builder.toString(); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/resources/0040755 0000000 0000000 00000000000 12613456027 022436 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/resources/org/0040755 0000000 0000000 00000000000 12613456027 023225 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/resources/org/apache/0040755 0000000 0000000 00000000000 12613456027 024446 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/resources/org/apache/http/0040755 0000000 0000000 00000000000 12613456027 025425 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/resources/org/apache/http/nio/0040755 0000000 0000000 00000000000 12613456027 026212 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/resources/org/apache/http/nio/version.properties0100644 0000000 0000000 00000001624 12613456027 032015 0ustar000000000 0000000 # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT 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-nio info.release = ${pom.version} info.timestamp = ${mvn.timestamp} # timestamp requires Maven 2.1 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/0040755 0000000 0000000 00000000000 12613456024 023440 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/0040755 0000000 0000000 00000000000 12613456024 024227 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/0040755 0000000 0000000 00000000000 12613456024 025450 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/0040755 0000000 0000000 00000000000 12613456024 026427 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/0040755 0000000 0000000 00000000000 12613456024 027214 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/params/0040755 0000000 0000000 00000000000 12613456024 030477 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000161 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/params/NIOReactorParams.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/params/NIOReacto0100644 0000000 0000000 00000011615 12613456024 032206 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.params; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Utility class for accessing I/O reactor parameters in {@link HttpParams}. * * @since 4.0 * * @see NIOReactorPNames * * @deprecated (4.2) use {@link org.apache.http.impl.nio.reactor.IOReactorConfig} */ @Deprecated public final class NIOReactorParams implements NIOReactorPNames { private NIOReactorParams() { super(); } /** * Obtains the value of {@link NIOReactorPNames#CONTENT_BUFFER_SIZE} parameter. * If not set, defaults to {@code 4096}. * * @param params HTTP parameters. * @return content buffer size. */ public static int getContentBufferSize(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getIntParameter(CONTENT_BUFFER_SIZE, 4096); } /** * Sets value of the {@link NIOReactorPNames#CONTENT_BUFFER_SIZE} parameter. * * @param params HTTP parameters. * @param size content buffer size. */ public static void setContentBufferSize(final HttpParams params, final int size) { Args.notNull(params, "HTTP parameters"); params.setIntParameter(CONTENT_BUFFER_SIZE, size); } /** * Obtains the value of {@link NIOReactorPNames#SELECT_INTERVAL} parameter. * If not set, defaults to {@code 1000}. * * @param params HTTP parameters. * @return I/O select interval in milliseconds. */ public static long getSelectInterval(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getLongParameter(SELECT_INTERVAL, 1000); } /** * Sets value of the {@link NIOReactorPNames#SELECT_INTERVAL} parameter. * * @param params HTTP parameters. * @param ms I/O select interval in milliseconds. */ public static void setSelectInterval(final HttpParams params, final long ms) { Args.notNull(params, "HTTP parameters"); params.setLongParameter(SELECT_INTERVAL, ms); } /** * Obtains the value of {@link NIOReactorPNames#GRACE_PERIOD} parameter. * If not set, defaults to {@code 500}. * * @param params HTTP parameters. * @return shutdown grace period in milliseconds. */ public static long getGracePeriod(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getLongParameter(GRACE_PERIOD, 500); } /** * Sets value of the {@link NIOReactorPNames#GRACE_PERIOD} parameter. * * @param params HTTP parameters. * @param ms shutdown grace period in milliseconds. */ public static void setGracePeriod(final HttpParams params, final long ms) { Args.notNull(params, "HTTP parameters"); params.setLongParameter(GRACE_PERIOD, ms); } /** * Obtains the value of {@link NIOReactorPNames#INTEREST_OPS_QUEUEING} parameter. * If not set, defaults to {@code false}. * * @param params HTTP parameters. * @return interest ops queuing flag. * * @since 4.1 */ public static boolean getInterestOpsQueueing(final HttpParams params) { Args.notNull(params, "HTTP parameters"); return params.getBooleanParameter(INTEREST_OPS_QUEUEING, false); } /** * Sets value of the {@link NIOReactorPNames#INTEREST_OPS_QUEUEING} parameter. * * @param params HTTP parameters. * @param interestOpsQueueing interest ops queuing. * * @since 4.1 */ public static void setInterestOpsQueueing( final HttpParams params, final boolean interestOpsQueueing) { Args.notNull(params, "HTTP parameters"); params.setBooleanParameter(INTEREST_OPS_QUEUEING, interestOpsQueueing); } } ././@LongLink0100644 0000000 0000000 00000000164 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/params/NIOReactorParamBean.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/params/NIOReacto0100644 0000000 0000000 00000003533 12613456024 032206 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.params; import org.apache.http.params.HttpAbstractParamBean; import org.apache.http.params.HttpParams; /** * @since 4.0 * * @deprecated (4.2) use {@link org.apache.http.impl.nio.reactor.IOReactorConfig} */ @Deprecated public class NIOReactorParamBean extends HttpAbstractParamBean { public NIOReactorParamBean (final HttpParams params) { super(params); } public void setContentBufferSize (final int contentBufferSize) { NIOReactorParams.setContentBufferSize(params, contentBufferSize); } public void setSelectInterval (final long selectInterval) { NIOReactorParams.setSelectInterval(params, selectInterval); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/0040755 0000000 0000000 00000000000 12613456024 031055 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000176 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRequestHandlerResolver.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRe0100644 0000000 0000000 00000003527 12613456024 032330 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; /** * HttpRequestHandlerResolver can be used to resolve an instance of * {@link NHttpRequestHandler} 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.2) use {@link HttpAsyncRequestHandlerResolver} */ @Deprecated public interface NHttpRequestHandlerResolver { /** * Looks up a handler matching the given request URI. * * @param requestURI the request URI * @return HTTP request handler or {@code null} if no match * is found. */ NHttpRequestHandler lookup(String requestURI); } ././@LongLink0100644 0000000 0000000 00000000176 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/ThrottlingHttpClientHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/Throttl0100644 0000000 0000000 00000061502 12613456024 032441 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.Executor; 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.HttpStatus; import org.apache.http.annotation.ThreadSafe; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.entity.ContentBufferEntity; import org.apache.http.nio.entity.ContentOutputStream; import org.apache.http.nio.params.NIOReactorPNames; import org.apache.http.nio.protocol.ThrottlingHttpServiceHandler.ServerConnState; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.ContentInputBuffer; import org.apache.http.nio.util.ContentOutputBuffer; import org.apache.http.nio.util.DirectByteBufferAllocator; import org.apache.http.nio.util.SharedInputBuffer; import org.apache.http.nio.util.SharedOutputBuffer; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; /** * Client protocol handler implementation that provide compatibility with * the blocking I/O by utilizing shared content buffers and a fairly small pool * of worker threads. The throttling protocol handler allocates input / output * buffers of a constant length upon initialization and controls the rate of * I/O events in order to ensure those content buffers do not ever get * overflown. This helps ensure nearly constant memory footprint for HTTP * connections and avoid the out of memory condition while streaming content * in and out. The {@link HttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)} * method will fire immediately when a message is received. The protocol handler * delegate the task of processing requests and generating response content to * an {@link Executor}, which is expected to perform those tasks using * dedicated worker threads in order to avoid blocking the I/O thread. *

* Usually throttling protocol handlers need only a modest number of worker * threads, much fewer than the number of concurrent connections. If the length * of the message is smaller or about the size of the shared content buffer * worker thread will just store content in the buffer and terminate almost * immediately without blocking. The I/O dispatch thread in its turn will take * care of sending out the buffered content asynchronously. The worker thread * will have to block only when processing large messages and the shared buffer * fills up. It is generally advisable to allocate shared buffers of a size of * an average content body for optimal performance. *

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

    *
  • {@link org.apache.http.nio.params.NIOReactorPNames#CONTENT_BUFFER_SIZE}
  • *
  • {@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}
  • *
* * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncRequestExecutor} and {@link HttpAsyncRequester} */ @Deprecated @ThreadSafe // provided injected dependencies are immutable or thread safe public class ThrottlingHttpClientHandler extends NHttpHandlerBase implements NHttpClientHandler { protected HttpRequestExecutionHandler execHandler; protected final Executor executor; private final int bufsize; public ThrottlingHttpClientHandler( final HttpProcessor httpProcessor, final HttpRequestExecutionHandler execHandler, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final Executor executor, final HttpParams params) { super(httpProcessor, connStrategy, allocator, params); Args.notNull(execHandler, "HTTP request execution handler"); Args.notNull(executor, "Executor"); this.execHandler = execHandler; this.executor = executor; this.bufsize = this.params.getIntParameter(NIOReactorPNames.CONTENT_BUFFER_SIZE, 20480); } public ThrottlingHttpClientHandler( final HttpProcessor httpProcessor, final HttpRequestExecutionHandler execHandler, final ConnectionReuseStrategy connStrategy, final Executor executor, final HttpParams params) { this(httpProcessor, execHandler, connStrategy, DirectByteBufferAllocator.INSTANCE, executor, params); } public void connected(final NHttpClientConnection conn, final Object attachment) { final HttpContext context = conn.getContext(); initialize(conn, attachment); final ClientConnState connState = new ClientConnState(this.bufsize, conn, this.allocator); context.setAttribute(CONN_STATE, connState); if (this.eventListener != null) { this.eventListener.connectionOpen(conn); } requestReady(conn); } public void closed(final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); if (connState != null) { synchronized (connState) { connState.close(); connState.notifyAll(); } } this.execHandler.finalizeContext(context); if (this.eventListener != null) { this.eventListener.connectionClosed(conn); } } public void exception(final NHttpClientConnection conn, final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } public void exception(final NHttpClientConnection conn, final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } public void requestReady(final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); try { synchronized (connState) { if (connState.getOutputState() != ClientConnState.READY) { return; } final HttpRequest request = this.execHandler.submitRequest(context); if (request == null) { return; } request.setParams( new DefaultedHttpParams(request.getParams(), this.params)); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); this.httpProcessor.process(request, context); connState.setRequest(request); conn.submitRequest(request); connState.setOutputState(ClientConnState.REQUEST_SENT); conn.requestInput(); if (request instanceof HttpEntityEnclosingRequest) { if (((HttpEntityEnclosingRequest) request).expectContinue()) { int timeout = conn.getSocketTimeout(); connState.setTimeout(timeout); timeout = this.params.getIntParameter( CoreProtocolPNames.WAIT_FOR_CONTINUE, 3000); conn.setSocketTimeout(timeout); connState.setOutputState(ClientConnState.EXPECT_CONTINUE); } else { sendRequestBody( (HttpEntityEnclosingRequest) request, connState, conn); } } connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); try { synchronized (connState) { if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) { conn.suspendOutput(); return; } final ContentOutputBuffer buffer = connState.getOutbuffer(); buffer.produceContent(encoder); if (encoder.isCompleted()) { connState.setInputState(ClientConnState.REQUEST_BODY_DONE); } else { connState.setInputState(ClientConnState.REQUEST_BODY_STREAM); } connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } public void responseReceived(final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); try { synchronized (connState) { final HttpResponse response = conn.getHttpResponse(); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); final HttpRequest request = connState.getRequest(); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < HttpStatus.SC_OK) { // 1xx intermediate response if (statusCode == HttpStatus.SC_CONTINUE && connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) { connState.setOutputState(ClientConnState.REQUEST_SENT); continueRequest(conn, connState); } return; } else { connState.setResponse(response); connState.setInputState(ClientConnState.RESPONSE_RECEIVED); if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) { final int timeout = connState.getTimeout(); conn.setSocketTimeout(timeout); conn.resetOutput(); } } if (!canResponseHaveBody(request, response)) { conn.resetInput(); response.setEntity(null); connState.setInputState(ClientConnState.RESPONSE_DONE); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } } if (response.getEntity() != null) { response.setEntity(new ContentBufferEntity( response.getEntity(), connState.getInbuffer())); } context.setAttribute(ExecutionContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); handleResponse(response, connState, conn); connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); try { synchronized (connState) { final HttpResponse response = connState.getResponse(); final ContentInputBuffer buffer = connState.getInbuffer(); buffer.consumeContent(decoder); if (decoder.isCompleted()) { connState.setInputState(ClientConnState.RESPONSE_BODY_DONE); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } } else { connState.setInputState(ClientConnState.RESPONSE_BODY_STREAM); } connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } public void timeout(final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); try { synchronized (connState) { if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) { connState.setOutputState(ClientConnState.REQUEST_SENT); continueRequest(conn, connState); connState.notifyAll(); return; } } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } handleTimeout(conn); } private void initialize( final NHttpClientConnection conn, final Object attachment) { final HttpContext context = conn.getContext(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); this.execHandler.initalizeContext(context, attachment); } private void continueRequest( final NHttpClientConnection conn, final ClientConnState connState) throws IOException { final HttpRequest request = connState.getRequest(); final int timeout = connState.getTimeout(); conn.setSocketTimeout(timeout); sendRequestBody( (HttpEntityEnclosingRequest) request, connState, conn); } /** * @throws IOException - not thrown currently */ private void sendRequestBody( final HttpEntityEnclosingRequest request, final ClientConnState connState, final NHttpClientConnection conn) throws IOException { final HttpEntity entity = request.getEntity(); if (entity != null) { this.executor.execute(new Runnable() { public void run() { try { // Block until previous request is fully processed and // the worker thread no longer holds the shared buffer synchronized (connState) { try { for (;;) { final int currentState = connState.getOutputState(); if (!connState.isWorkerRunning()) { break; } if (currentState == ServerConnState.SHUTDOWN) { return; } connState.wait(); } } catch (final InterruptedException ex) { connState.shutdown(); return; } connState.setWorkerRunning(true); } final OutputStream outstream = new ContentOutputStream( connState.getOutbuffer()); request.getEntity().writeTo(outstream); outstream.flush(); outstream.close(); synchronized (connState) { connState.setWorkerRunning(false); connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (eventListener != null) { eventListener.fatalIOException(ex, conn); } } } }); } } private void handleResponse( final HttpResponse response, final ClientConnState connState, final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); this.executor.execute(new Runnable() { public void run() { try { // Block until previous request is fully processed and // the worker thread no longer holds the shared buffer synchronized (connState) { try { for (;;) { final int currentState = connState.getOutputState(); if (!connState.isWorkerRunning()) { break; } if (currentState == ServerConnState.SHUTDOWN) { return; } connState.wait(); } } catch (final InterruptedException ex) { connState.shutdown(); return; } connState.setWorkerRunning(true); } execHandler.handleResponse(response, context); synchronized (connState) { try { for (;;) { final int currentState = connState.getInputState(); if (currentState == ClientConnState.RESPONSE_DONE) { break; } if (currentState == ServerConnState.SHUTDOWN) { return; } connState.wait(); } } catch (final InterruptedException ex) { connState.shutdown(); } connState.resetInput(); connState.resetOutput(); if (conn.isOpen()) { conn.requestOutput(); } connState.setWorkerRunning(false); connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (eventListener != null) { eventListener.fatalIOException(ex, conn); } } } }); } static class ClientConnState { public static final int SHUTDOWN = -1; public static final int READY = 0; public static final int REQUEST_SENT = 1; public static final int EXPECT_CONTINUE = 2; public static final int REQUEST_BODY_STREAM = 4; public static final int REQUEST_BODY_DONE = 8; public static final int RESPONSE_RECEIVED = 16; public static final int RESPONSE_BODY_STREAM = 32; public static final int RESPONSE_BODY_DONE = 64; public static final int RESPONSE_DONE = 64; private final SharedInputBuffer inbuffer; private final SharedOutputBuffer outbuffer; private volatile int inputState; private volatile int outputState; private volatile HttpRequest request; private volatile HttpResponse response; private volatile int timeout; private volatile boolean workerRunning; public ClientConnState( final int bufsize, final IOControl ioControl, final ByteBufferAllocator allocator) { super(); this.inbuffer = new SharedInputBuffer(bufsize, ioControl, allocator); this.outbuffer = new SharedOutputBuffer(bufsize, ioControl, allocator); this.inputState = READY; this.outputState = READY; } public ContentInputBuffer getInbuffer() { return this.inbuffer; } public ContentOutputBuffer getOutbuffer() { return this.outbuffer; } public int getInputState() { return this.inputState; } public void setInputState(final int inputState) { this.inputState = inputState; } public int getOutputState() { return this.outputState; } public void setOutputState(final int outputState) { this.outputState = outputState; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public int getTimeout() { return this.timeout; } public void setTimeout(final int timeout) { this.timeout = timeout; } public boolean isWorkerRunning() { return this.workerRunning; } public void setWorkerRunning(final boolean b) { this.workerRunning = b; } public void close() { this.inbuffer.close(); this.outbuffer.close(); this.inputState = SHUTDOWN; this.outputState = SHUTDOWN; } public void shutdown() { this.inbuffer.shutdown(); this.outbuffer.shutdown(); this.inputState = SHUTDOWN; this.outputState = SHUTDOWN; } public void resetInput() { this.inbuffer.reset(); this.request = null; this.inputState = READY; } public void resetOutput() { this.outbuffer.reset(); this.response = null; this.outputState = READY; } } } ././@LongLink0100644 0000000 0000000 00000000172 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/AsyncNHttpClientHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/AsyncNH0100644 0000000 0000000 00000045616 12613456024 032314 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.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.HttpStatus; import org.apache.http.annotation.Immutable; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.NHttpEntityWrapper; import org.apache.http.nio.entity.ProducingNHttpEntity; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; /** * Fully asynchronous HTTP client side protocol handler that implements the * essential requirements of the HTTP protocol for the server side message * processing as described by RFC 2616. It is capable of executing HTTP requests * with nearly constant memory footprint. Only HTTP message heads are stored in * memory, while content of message bodies is streamed directly from the entity * to the underlying channel (and vice versa) using {@link ConsumingNHttpEntity} * and {@link ProducingNHttpEntity} interfaces. * * When using this implementation, it is important to ensure that entities * supplied for writing implement {@link ProducingNHttpEntity}. Doing so will allow * the entity to be written out asynchronously. If entities supplied for writing * do not implement the {@link ProducingNHttpEntity} interface, a delegate is * added that buffers the entire contents in memory. Additionally, the * buffering might take place in the I/O dispatch thread, which could cause I/O * to block temporarily. For best results, one must ensure that all entities * set on {@link HttpRequest}s from {@link NHttpRequestExecutionHandler} * implement {@link ProducingNHttpEntity}. * * If incoming responses enclose a content entity, * {@link NHttpRequestExecutionHandler} are expected to return a * {@link ConsumingNHttpEntity} for reading the content. After the entity is * finished reading the data, * {@link NHttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)} * method is called to process the response. *

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

    *
  • {@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}
  • *
* * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncRequestExecutor} and {@link HttpAsyncRequester} */ @Deprecated @Immutable // provided injected dependencies are immutable public class AsyncNHttpClientHandler extends NHttpHandlerBase implements NHttpClientHandler { protected NHttpRequestExecutionHandler execHandler; public AsyncNHttpClientHandler( final HttpProcessor httpProcessor, final NHttpRequestExecutionHandler execHandler, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final HttpParams params) { super(httpProcessor, connStrategy, allocator, params); this.execHandler = Args.notNull(execHandler, "HTTP request execution handler"); } public AsyncNHttpClientHandler( final HttpProcessor httpProcessor, final NHttpRequestExecutionHandler execHandler, final ConnectionReuseStrategy connStrategy, final HttpParams params) { this(httpProcessor, execHandler, connStrategy, HeapByteBufferAllocator.INSTANCE, params); } public void connected(final NHttpClientConnection conn, final Object attachment) { final HttpContext context = conn.getContext(); initialize(conn, attachment); final ClientConnState connState = new ClientConnState(); context.setAttribute(CONN_STATE, connState); if (this.eventListener != null) { this.eventListener.connectionOpen(conn); } requestReady(conn); } public void closed(final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); try { connState.reset(); } catch (final IOException ex) { if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } this.execHandler.finalizeContext(context); if (this.eventListener != null) { this.eventListener.connectionClosed(conn); } } public void exception(final NHttpClientConnection conn, final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } public void exception(final NHttpClientConnection conn, final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } public void requestReady(final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); if (connState.getOutputState() != ClientConnState.READY) { return; } try { final HttpRequest request = this.execHandler.submitRequest(context); if (request == null) { return; } request.setParams( new DefaultedHttpParams(request.getParams(), this.params)); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); this.httpProcessor.process(request, context); HttpEntityEnclosingRequest entityReq = null; HttpEntity entity = null; if (request instanceof HttpEntityEnclosingRequest) { entityReq = (HttpEntityEnclosingRequest) request; entity = entityReq.getEntity(); } if (entity instanceof ProducingNHttpEntity) { connState.setProducingEntity((ProducingNHttpEntity) entity); } else if (entity != null) { connState.setProducingEntity(new NHttpEntityWrapper(entity)); } connState.setRequest(request); conn.submitRequest(request); connState.setOutputState(ClientConnState.REQUEST_SENT); if (entityReq != null && entityReq.expectContinue()) { int timeout = conn.getSocketTimeout(); connState.setTimeout(timeout); timeout = this.params.getIntParameter( CoreProtocolPNames.WAIT_FOR_CONTINUE, 3000); conn.setSocketTimeout(timeout); connState.setOutputState(ClientConnState.EXPECT_CONTINUE); } else if (connState.getProducingEntity() != null) { connState.setOutputState(ClientConnState.REQUEST_BODY_STREAM); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); final ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity(); try { consumingEntity.consumeContent(decoder, conn); if (decoder.isCompleted()) { processResponse(conn, connState); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); try { if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) { conn.suspendOutput(); return; } final ProducingNHttpEntity entity = connState.getProducingEntity(); entity.produceContent(encoder, conn); if (encoder.isCompleted()) { connState.setOutputState(ClientConnState.REQUEST_BODY_DONE); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } public void responseReceived(final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); final HttpResponse response = conn.getHttpResponse(); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); final HttpRequest request = connState.getRequest(); try { final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < HttpStatus.SC_OK) { // 1xx intermediate response if (statusCode == HttpStatus.SC_CONTINUE && connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) { continueRequest(conn, connState); } return; } else { connState.setResponse(response); if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) { cancelRequest(conn, connState); } else if (connState.getOutputState() == ClientConnState.REQUEST_BODY_STREAM) { // Early response cancelRequest(conn, connState); connState.invalidate(); conn.suspendOutput(); } } context.setAttribute(ExecutionContext.HTTP_RESPONSE, response); if (!canResponseHaveBody(request, response)) { conn.resetInput(); response.setEntity(null); this.httpProcessor.process(response, context); processResponse(conn, connState); } else { final HttpEntity entity = response.getEntity(); if (entity != null) { ConsumingNHttpEntity consumingEntity = this.execHandler.responseEntity( response, context); if (consumingEntity == null) { consumingEntity = new NullNHttpEntity(entity); } response.setEntity(consumingEntity); connState.setConsumingEntity(consumingEntity); this.httpProcessor.process(response, context); } } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void timeout(final NHttpClientConnection conn) { final HttpContext context = conn.getContext(); final ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE); try { if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) { continueRequest(conn, connState); return; } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } handleTimeout(conn); } private void initialize( final NHttpClientConnection conn, final Object attachment) { final HttpContext context = conn.getContext(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); this.execHandler.initalizeContext(context, attachment); } /** * @throws IOException - not thrown currently */ private void continueRequest( final NHttpClientConnection conn, final ClientConnState connState) throws IOException { final int timeout = connState.getTimeout(); conn.setSocketTimeout(timeout); conn.requestOutput(); connState.setOutputState(ClientConnState.REQUEST_BODY_STREAM); } private void cancelRequest( final NHttpClientConnection conn, final ClientConnState connState) throws IOException { final int timeout = connState.getTimeout(); conn.setSocketTimeout(timeout); conn.resetOutput(); connState.resetOutput(); } /** * @throws HttpException - not thrown currently */ private void processResponse( final NHttpClientConnection conn, final ClientConnState connState) throws IOException, HttpException { if (!connState.isValid()) { conn.close(); } final HttpContext context = conn.getContext(); final HttpResponse response = connState.getResponse(); this.execHandler.handleResponse(response, context); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } if (conn.isOpen()) { // Ready for another request connState.resetInput(); connState.resetOutput(); conn.requestOutput(); } } protected static class ClientConnState { public static final int READY = 0; public static final int REQUEST_SENT = 1; public static final int EXPECT_CONTINUE = 2; public static final int REQUEST_BODY_STREAM = 4; public static final int REQUEST_BODY_DONE = 8; public static final int RESPONSE_RECEIVED = 16; public static final int RESPONSE_BODY_STREAM = 32; public static final int RESPONSE_BODY_DONE = 64; private int outputState; private HttpRequest request; private HttpResponse response; private ConsumingNHttpEntity consumingEntity; private ProducingNHttpEntity producingEntity; private boolean valid; private int timeout; public ClientConnState() { super(); this.valid = true; } public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) { this.consumingEntity = consumingEntity; } public void setProducingEntity(final ProducingNHttpEntity producingEntity) { this.producingEntity = producingEntity; } public ProducingNHttpEntity getProducingEntity() { return producingEntity; } public ConsumingNHttpEntity getConsumingEntity() { return consumingEntity; } public int getOutputState() { return this.outputState; } public void setOutputState(final int outputState) { this.outputState = outputState; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public int getTimeout() { return this.timeout; } public void setTimeout(final int timeout) { this.timeout = timeout; } public void resetInput() throws IOException { this.response = null; if (this.consumingEntity != null) { this.consumingEntity.finish(); this.consumingEntity = null; } } public void resetOutput() throws IOException { this.request = null; if (this.producingEntity != null) { this.producingEntity.finish(); this.producingEntity = null; } this.outputState = READY; } public void reset() throws IOException { resetInput(); resetOutput(); } public boolean isValid() { return this.valid; } public void invalidate() { this.valid = false; } } } ././@LongLink0100644 0000000 0000000 00000000163 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpHandlerBase.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpHa0100644 0000000 0000000 00000011213 12613456024 032301 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.annotation.Immutable; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; /** * @since 4.0 * * @deprecated (4.2) do not use */ @Deprecated @Immutable // provided injected dependencies are immutable public abstract class NHttpHandlerBase { protected static final String CONN_STATE = "http.nio.conn-state"; protected final HttpProcessor httpProcessor; protected final ConnectionReuseStrategy connStrategy; protected final ByteBufferAllocator allocator; protected final HttpParams params; protected EventListener eventListener; public NHttpHandlerBase( final HttpProcessor httpProcessor, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final HttpParams params) { super(); Args.notNull(httpProcessor, "HTTP processor"); Args.notNull(connStrategy, "Connection reuse strategy"); Args.notNull(allocator, "ByteBuffer allocator"); Args.notNull(params, "HTTP parameters"); this.httpProcessor = httpProcessor; this.connStrategy = connStrategy; this.allocator = allocator; this.params = params; } public HttpParams getParams() { return this.params; } public void setEventListener(final EventListener eventListener) { this.eventListener = eventListener; } protected void closeConnection(final NHttpConnection conn, final Throwable cause) { try { // Try to close it nicely conn.close(); } catch (final IOException ex) { try { // Just shut the damn thing down conn.shutdown(); } catch (final IOException ignore) { } } } protected void shutdownConnection(final NHttpConnection conn, final Throwable cause) { try { conn.shutdown(); } catch (final IOException ignore) { } } protected void handleTimeout(final NHttpConnection conn) { try { if (conn.getStatus() == NHttpConnection.ACTIVE) { conn.close(); if (conn.getStatus() == NHttpConnection.CLOSING) { // Give the connection some grace time to // close itself nicely conn.setSocketTimeout(250); } if (this.eventListener != null) { this.eventListener.connectionTimeout(conn); } } else { conn.shutdown(); } } catch (final IOException ignore) { } } protected boolean canResponseHaveBody( final HttpRequest request, final HttpResponse response) { if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { return false; } final int status = response.getStatusLine().getStatusCode(); return status >= HttpStatus.SC_OK && status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT; } } ././@LongLink0100644 0000000 0000000 00000000175 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/BufferingHttpClientHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/Bufferi0100644 0000000 0000000 00000015051 12613456024 032361 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.annotation.Immutable; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.entity.BufferingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; /** * Client protocol handler implementation that provides compatibility with the * blocking I/O by storing the full content of HTTP messages in memory. * The {@link HttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)} * method will fire only when the entire message content has been read into a * in-memory buffer. Please note that request execution / response processing * take place the main I/O thread and therefore * {@link HttpRequestExecutionHandler} methods should not block indefinitely. *

* When using this protocol handler {@link org.apache.http.HttpEntity}'s content * can be generated / consumed using standard {@link java.io.InputStream}/ * {@link java.io.OutputStream} classes. *

* IMPORTANT: This protocol handler should be used only when dealing with HTTP * messages that are known to be limited in length. * * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncRequestExecutor} and {@link HttpAsyncRequester} */ @Deprecated @Immutable // provided injected dependencies are immutable public class BufferingHttpClientHandler implements NHttpClientHandler { private final AsyncNHttpClientHandler asyncHandler; public BufferingHttpClientHandler( final HttpProcessor httpProcessor, final HttpRequestExecutionHandler execHandler, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final HttpParams params) { this.asyncHandler = new AsyncNHttpClientHandler( httpProcessor, new ExecutionHandlerAdaptor(execHandler), connStrategy, allocator, params); } public BufferingHttpClientHandler( final HttpProcessor httpProcessor, final HttpRequestExecutionHandler execHandler, final ConnectionReuseStrategy connStrategy, final HttpParams params) { this(httpProcessor, execHandler, connStrategy, HeapByteBufferAllocator.INSTANCE, params); } public void setEventListener(final EventListener eventListener) { this.asyncHandler.setEventListener(eventListener); } public void connected(final NHttpClientConnection conn, final Object attachment) { this.asyncHandler.connected(conn, attachment); } public void closed(final NHttpClientConnection conn) { this.asyncHandler.closed(conn); } public void requestReady(final NHttpClientConnection conn) { this.asyncHandler.requestReady(conn); } public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) { this.asyncHandler.inputReady(conn, decoder); } public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) { this.asyncHandler.outputReady(conn, encoder); } public void responseReceived(final NHttpClientConnection conn) { this.asyncHandler.responseReceived(conn); } public void exception(final NHttpClientConnection conn, final HttpException httpex) { this.asyncHandler.exception(conn, httpex); } public void exception(final NHttpClientConnection conn, final IOException ioex) { this.asyncHandler.exception(conn, ioex); } public void timeout(final NHttpClientConnection conn) { this.asyncHandler.timeout(conn); } static class ExecutionHandlerAdaptor implements NHttpRequestExecutionHandler { private final HttpRequestExecutionHandler execHandler; public ExecutionHandlerAdaptor(final HttpRequestExecutionHandler execHandler) { super(); this.execHandler = execHandler; } public void initalizeContext(final HttpContext context, final Object attachment) { this.execHandler.initalizeContext(context, attachment); } public void finalizeContext(final HttpContext context) { this.execHandler.finalizeContext(context); } public HttpRequest submitRequest(final HttpContext context) { return this.execHandler.submitRequest(context); } public ConsumingNHttpEntity responseEntity( final HttpResponse response, final HttpContext context) throws IOException { return new BufferingNHttpEntity( response.getEntity(), HeapByteBufferAllocator.INSTANCE); } public void handleResponse( final HttpResponse response, final HttpContext context) throws IOException { this.execHandler.handleResponse(response, context); } } } ././@LongLink0100644 0000000 0000000 00000000173 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/AsyncNHttpServiceHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/AsyncNH0100644 0000000 0000000 00000062732 12613456024 032312 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.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.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.UnsupportedHttpVersionException; import org.apache.http.annotation.Immutable; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.NByteArrayEntity; import org.apache.http.nio.entity.NHttpEntityWrapper; import org.apache.http.nio.entity.ProducingNHttpEntity; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; import org.apache.http.util.Asserts; import org.apache.http.util.EncodingUtils; /** * Fully asynchronous HTTP server side protocol handler implementation that * implements the essential requirements of the HTTP protocol for the server * side message processing as described by RFC 2616. It is capable of processing * HTTP requests with nearly constant memory footprint. Only HTTP message heads * are stored in memory, while content of message bodies is streamed directly * from the entity to the underlying channel (and vice versa) * {@link ConsumingNHttpEntity} and {@link ProducingNHttpEntity} interfaces. *

* When using this class, it is important to ensure that entities supplied for * writing implement {@link ProducingNHttpEntity}. Doing so will allow the * entity to be written out asynchronously. If entities supplied for writing do * not implement {@link ProducingNHttpEntity}, a delegate is added that buffers * the entire contents in memory. Additionally, the buffering might take place * in the I/O thread, which could cause I/O to block temporarily. For best * results, ensure that all entities set on {@link HttpResponse}s from * {@link NHttpRequestHandler}s implement {@link ProducingNHttpEntity}. *

* If incoming requests enclose a content entity, {@link NHttpRequestHandler}s * are expected to return a {@link ConsumingNHttpEntity} for reading the * content. After the entity is finished reading the data, * {@link NHttpRequestHandler#handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)} * is called to generate a response. *

* Individual {@link NHttpRequestHandler}s do not have to submit a response * immediately. They can defer transmission of the HTTP response back to the * client without blocking the I/O thread and to delegate the processing the * HTTP request to a worker thread. The worker thread in its turn can use an * instance of {@link NHttpResponseTrigger} passed as a parameter to submit * a response as at a later point of time once the response becomes available. * * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncService} */ @Deprecated @Immutable // provided injected dependencies are immutable public class AsyncNHttpServiceHandler extends NHttpHandlerBase implements NHttpServiceHandler { protected final HttpResponseFactory responseFactory; protected NHttpRequestHandlerResolver handlerResolver; protected HttpExpectationVerifier expectationVerifier; public AsyncNHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final HttpParams params) { super(httpProcessor, connStrategy, allocator, params); Args.notNull(responseFactory, "Response factory"); this.responseFactory = responseFactory; } public AsyncNHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final HttpParams params) { this(httpProcessor, responseFactory, connStrategy, HeapByteBufferAllocator.INSTANCE, params); } public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; } public void setHandlerResolver(final NHttpRequestHandlerResolver handlerResolver) { this.handlerResolver = handlerResolver; } public void connected(final NHttpServerConnection conn) { final HttpContext context = conn.getContext(); final ServerConnState connState = new ServerConnState(); context.setAttribute(CONN_STATE, connState); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); if (this.eventListener != null) { this.eventListener.connectionOpen(conn); } } public void requestReceived(final NHttpServerConnection conn) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); final HttpRequest request = conn.getHttpRequest(); request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); connState.setRequest(request); final NHttpRequestHandler requestHandler = getRequestHandler(request); connState.setRequestHandler(requestHandler); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } HttpResponse response; try { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; if (entityRequest.expectContinue()) { response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); 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); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(ex, response); } } if (response.getStatusLine().getStatusCode() < 200) { // Send 1xx response indicating the server expections // have been met conn.submitResponse(response); } else { conn.resetInput(); sendResponse(conn, request, response); } } // Request content is expected. ConsumingNHttpEntity consumingEntity = null; // Lookup request handler for this request if (requestHandler != null) { consumingEntity = requestHandler.entityRequest(entityRequest, context); } if (consumingEntity == null) { consumingEntity = new NullNHttpEntity(entityRequest.getEntity()); } entityRequest.setEntity(consumingEntity); connState.setConsumingEntity(consumingEntity); } else { // No request content is expected. // Process request right away conn.suspendInput(); processRequest(conn, request); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void closed(final NHttpServerConnection conn) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); try { connState.reset(); } catch (final IOException ex) { if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } if (this.eventListener != null) { this.eventListener.connectionClosed(conn); } } public void exception(final NHttpServerConnection conn, final HttpException httpex) { if (conn.isResponseSubmitted()) { // There is not much that we can do if a response head // has already been submitted closeConnection(conn, httpex); if (eventListener != null) { eventListener.fatalProtocolException(httpex, conn); } return; } final HttpContext context = conn.getContext(); try { final HttpResponse response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); response.setEntity(null); sendResponse(conn, null, response); } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void exception(final NHttpServerConnection conn, final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } public void timeout(final NHttpServerConnection conn) { handleTimeout(conn); } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); final HttpRequest request = connState.getRequest(); final ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity(); try { consumingEntity.consumeContent(decoder, conn); if (decoder.isCompleted()) { conn.suspendInput(); processRequest(conn, request); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void responseReady(final NHttpServerConnection conn) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); if (connState.isHandled()) { return; } final HttpRequest request = connState.getRequest(); try { final IOException ioex = connState.getIOException(); if (ioex != null) { throw ioex; } final HttpException httpex = connState.getHttpException(); if (httpex != null) { final HttpResponse response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); connState.setResponse(response); } final HttpResponse response = connState.getResponse(); if (response != null) { connState.setHandled(true); sendResponse(conn, request, response); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); final HttpResponse response = conn.getHttpResponse(); try { final ProducingNHttpEntity entity = connState.getProducingEntity(); entity.produceContent(encoder, conn); if (encoder.isCompleted()) { connState.finishOutput(); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready to process new request connState.reset(); conn.requestInput(); } responseComplete(response, context); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } private void handleException(final HttpException ex, final HttpResponse response) { int code = HttpStatus.SC_INTERNAL_SERVER_ERROR; if (ex instanceof MethodNotSupportedException) { code = HttpStatus.SC_NOT_IMPLEMENTED; } else if (ex instanceof UnsupportedHttpVersionException) { code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED; } else if (ex instanceof ProtocolException) { code = HttpStatus.SC_BAD_REQUEST; } response.setStatusCode(code); final byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage()); final NByteArrayEntity entity = new NByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); } /** * @throws HttpException - not thrown currently */ private void processRequest( final NHttpServerConnection conn, final HttpRequest request) throws IOException, HttpException { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } final NHttpResponseTrigger trigger = new ResponseTriggerImpl(connState, conn); try { this.httpProcessor.process(request, context); final NHttpRequestHandler handler = connState.getRequestHandler(); if (handler != null) { final HttpResponse response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_OK, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handler.handle( request, response, trigger, context); } else { final HttpResponse response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_NOT_IMPLEMENTED, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); trigger.submitResponse(response); } } catch (final HttpException ex) { trigger.handleException(ex); } } private void sendResponse( final NHttpServerConnection conn, final HttpRequest request, final HttpResponse response) throws IOException, HttpException { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); // Now that a response is ready, we can cleanup the listener for the request. connState.finishInput(); // Some processers need the request that generated this response. context.setAttribute(ExecutionContext.HTTP_REQUEST, request); this.httpProcessor.process(response, context); context.setAttribute(ExecutionContext.HTTP_REQUEST, null); if (response.getEntity() != null && !canResponseHaveBody(request, response)) { response.setEntity(null); } final HttpEntity entity = response.getEntity(); if (entity != null) { if (entity instanceof ProducingNHttpEntity) { connState.setProducingEntity((ProducingNHttpEntity) entity); } else { connState.setProducingEntity(new NHttpEntityWrapper(entity)); } } conn.submitResponse(response); if (entity == null) { if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready to process new request connState.reset(); conn.requestInput(); } responseComplete(response, context); } } /** * Signals that this response has been fully sent. This will be called after * submitting the response to a connection, if there is no entity in the * response. If there is an entity, it will be called after the entity has * completed. */ protected void responseComplete(final HttpResponse response, final HttpContext context) { } private NHttpRequestHandler getRequestHandler(final HttpRequest request) { NHttpRequestHandler handler = null; if (this.handlerResolver != null) { final String requestURI = request.getRequestLine().getUri(); handler = this.handlerResolver.lookup(requestURI); } return handler; } protected static class ServerConnState { private volatile NHttpRequestHandler requestHandler; private volatile HttpRequest request; private volatile ConsumingNHttpEntity consumingEntity; private volatile HttpResponse response; private volatile ProducingNHttpEntity producingEntity; private volatile IOException ioex; private volatile HttpException httpex; private volatile boolean handled; public void finishInput() throws IOException { if (this.consumingEntity != null) { this.consumingEntity.finish(); this.consumingEntity = null; } } public void finishOutput() throws IOException { if (this.producingEntity != null) { this.producingEntity.finish(); this.producingEntity = null; } } public void reset() throws IOException { finishInput(); this.request = null; finishOutput(); this.handled = false; this.response = null; this.ioex = null; this.httpex = null; this.requestHandler = null; } public NHttpRequestHandler getRequestHandler() { return this.requestHandler; } public void setRequestHandler(final NHttpRequestHandler requestHandler) { this.requestHandler = requestHandler; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public ConsumingNHttpEntity getConsumingEntity() { return this.consumingEntity; } public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) { this.consumingEntity = consumingEntity; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public ProducingNHttpEntity getProducingEntity() { return this.producingEntity; } public void setProducingEntity(final ProducingNHttpEntity producingEntity) { this.producingEntity = producingEntity; } public IOException getIOException() { return this.ioex; } public IOException getIOExepction() { return this.ioex; } public void setIOException(final IOException ex) { this.ioex = ex; } public void setIOExepction(final IOException ex) { this.ioex = ex; } public HttpException getHttpException() { return this.httpex; } public HttpException getHttpExepction() { return this.httpex; } public void setHttpException(final HttpException ex) { this.httpex = ex; } public void setHttpExepction(final HttpException ex) { this.httpex = ex; } public boolean isHandled() { return this.handled; } public void setHandled(final boolean handled) { this.handled = handled; } } private static class ResponseTriggerImpl implements NHttpResponseTrigger { private final ServerConnState connState; private final IOControl iocontrol; private volatile boolean triggered; public ResponseTriggerImpl(final ServerConnState connState, final IOControl iocontrol) { super(); this.connState = connState; this.iocontrol = iocontrol; } public void submitResponse(final HttpResponse response) { Args.notNull(response, "Response"); Asserts.check(!this.triggered, "Response already triggered"); this.triggered = true; this.connState.setResponse(response); this.iocontrol.requestOutput(); } public void handleException(final HttpException ex) { Asserts.check(!this.triggered, "Response already triggered"); this.triggered = true; this.connState.setHttpException(ex); this.iocontrol.requestOutput(); } public void handleException(final IOException ex) { Asserts.check(!this.triggered, "Response already triggered"); this.triggered = true; this.connState.setIOException(ex); this.iocontrol.requestOutput(); } } } ././@LongLink0100644 0000000 0000000 00000000176 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/HttpRequestExecutionHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/HttpReq0100644 0000000 0000000 00000007026 12613456024 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.nio.protocol; import java.io.IOException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.protocol.HttpContext; /** * HTTP request execution handler can be used by client-side protocol handlers * to trigger the submission of a new HTTP request and the processing of an * HTTP response. * * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncRequestExecutor} and {@link HttpAsyncRequester} */ @Deprecated public interface HttpRequestExecutionHandler { /** * Triggered when a new connection has been established and the * HTTP context needs to be initialized. * *

The attachment object is the same object which was passed * to the connecting I/O reactor when the connection request was * made. The attachment may optionally contain some state information * required in order to correctly initialize the HTTP context. * * @see org.apache.http.nio.reactor.ConnectingIOReactor#connect * * @param context the actual HTTP context * @param attachment the object passed to the connecting I/O reactor * upon the request for a new connection. */ void initalizeContext(HttpContext context, Object attachment); /** * Triggered when the underlying connection is ready to send a new * HTTP request to the target host. This method may return * {@code null} if the client is not yet ready to send a * request. In this case the connection will remain open and * can be activated at a later point. * * @param context the actual HTTP context * @return an HTTP request to be sent or {@code null} if no * request needs to be sent */ HttpRequest submitRequest(HttpContext context); /** * Triggered when an HTTP response is ready to be processed. * * @param response the HTTP response to be processed * @param context the actual HTTP context * @throws IOException if a problem is encountered */ void handleResponse(HttpResponse response, HttpContext context) throws IOException; /** * Triggered when the connection is terminated. This event can be used * to release objects stored in the context or perform some other kind * of cleanup. * * @param context the actual HTTP context */ void finalizeContext(HttpContext context); } ././@LongLink0100644 0000000 0000000 00000000202 12613460517 011632 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/HttpAsyncRequestHandlerRegistry.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/HttpAsy0100644 0000000 0000000 00000006574 12613456024 032405 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.util.Map; import org.apache.http.annotation.ThreadSafe; import org.apache.http.protocol.UriPatternMatcher; /** * Maintains a map of HTTP request handlers keyed by a request URI pattern. *
* Patterns may have three formats: *

    *
  • {@code *}
  • *
  • {@code *<uri>}
  • *
  • {@code <uri>*}
  • *
*
* This class can be used to resolve an instance of {@link HttpAsyncRequestHandler} * matching a particular request URI. Usually the resolved request handler * will be used to process the request with the specified request URI. * * @since 4.2 * @deprecated (4.3) use {@link UriHttpAsyncRequestHandlerMapper} */ @ThreadSafe @Deprecated public class HttpAsyncRequestHandlerRegistry implements HttpAsyncRequestHandlerResolver { private final UriPatternMatcher> matcher; public HttpAsyncRequestHandlerRegistry() { matcher = new UriPatternMatcher>(); } /** * Registers the given {@link HttpAsyncRequestHandler} 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 HttpAsyncRequestHandler 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. */ public Map> getHandlers() { return matcher.getObjects(); } public HttpAsyncRequestHandler lookup(final String requestURI) { return matcher.lookup(requestURI); } } ././@LongLink0100644 0000000 0000000 00000000176 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRequestHandlerRegistry.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRe0100644 0000000 0000000 00000006443 12613456024 032330 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.util.Map; import org.apache.http.protocol.UriPatternMatcher; /** * Maintains a map of HTTP request handlers keyed by a request URI pattern. *
* Patterns may have three formats: *
    *
  • {@code *}
  • *
  • {@code *<uri>}
  • *
  • {@code <uri>*}
  • *
*
* This class can be used to resolve an instance of * {@link NHttpRequestHandler} 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.2) use {@link UriHttpAsyncRequestHandlerMapper} */ @Deprecated public class NHttpRequestHandlerRegistry implements NHttpRequestHandlerResolver { private final UriPatternMatcher matcher; public NHttpRequestHandlerRegistry() { matcher = new UriPatternMatcher(); } /** * Registers the given {@link NHttpRequestHandler} 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 NHttpRequestHandler 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 NHttpRequestHandler lookup(final String requestURI) { return matcher.lookup(requestURI); } } ././@LongLink0100644 0000000 0000000 00000000204 12613460517 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/BasicAsyncRequestExecutionHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/BasicAs0100644 0000000 0000000 00000016437 12613456024 032315 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import java.util.concurrent.Future; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.concurrent.BasicFuture; import org.apache.http.concurrent.FutureCallback; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.Args; /** * Basic implementation of {@link HttpAsyncRequestExecutionHandler} that executes * a single HTTP request / response exchange. * * @param the result type of request execution. * @since 4.2 * * @deprecated (4.3) use {@link BasicAsyncClientExchangeHandler}. */ @Deprecated public class BasicAsyncRequestExecutionHandler implements HttpAsyncRequestExecutionHandler { private final HttpAsyncRequestProducer requestProducer; private final HttpAsyncResponseConsumer responseConsumer; private final BasicFuture future; private final HttpContext localContext; private final HttpProcessor httppocessor; private final ConnectionReuseStrategy reuseStrategy; private volatile boolean requestSent; public BasicAsyncRequestExecutionHandler( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final FutureCallback callback, final HttpContext localContext, final HttpProcessor httppocessor, final ConnectionReuseStrategy reuseStrategy, final HttpParams params) { super(); Args.notNull(requestProducer, "Request producer"); Args.notNull(responseConsumer, "Response consumer"); Args.notNull(localContext, "HTTP context"); Args.notNull(httppocessor, "HTTP processor"); Args.notNull(reuseStrategy, "Connection reuse strategy"); Args.notNull(params, "HTTP parameters"); this.requestProducer = requestProducer; this.responseConsumer = responseConsumer; this.future = new BasicFuture(callback); this.localContext = localContext; this.httppocessor = httppocessor; this.reuseStrategy = reuseStrategy; } public BasicAsyncRequestExecutionHandler( final HttpAsyncRequestProducer requestProducer, final HttpAsyncResponseConsumer responseConsumer, final HttpContext localContext, final HttpProcessor httppocessor, final ConnectionReuseStrategy reuseStrategy, final HttpParams params) { this(requestProducer, responseConsumer, null, localContext, httppocessor, reuseStrategy, params); } public Future getFuture() { return this.future; } private void releaseResources() { try { this.responseConsumer.close(); } catch (final IOException ex) { } try { this.requestProducer.close(); } catch (final IOException ex) { } } public void close() throws IOException { releaseResources(); if (!this.future.isDone()) { this.future.cancel(); } } public HttpHost getTarget() { return this.requestProducer.getTarget(); } public HttpRequest generateRequest() throws IOException, HttpException { return this.requestProducer.generateRequest(); } public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { this.requestProducer.produceContent(encoder, ioctrl); } public void requestCompleted(final HttpContext context) { this.requestProducer.requestCompleted(context); this.requestSent = true; } public boolean isRepeatable() { return false; } public void resetRequest() { } public void responseReceived(final HttpResponse response) throws IOException, HttpException { this.responseConsumer.responseReceived(response); } public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { this.responseConsumer.consumeContent(decoder, ioctrl); } public void failed(final Exception ex) { try { if (!this.requestSent) { this.requestProducer.failed(ex); } this.responseConsumer.failed(ex); } finally { try { this.future.failed(ex); } finally { releaseResources(); } } } public boolean cancel() { try { final boolean cancelled = this.responseConsumer.cancel(); this.future.cancel(); releaseResources(); return cancelled; } catch (final RuntimeException ex) { failed(ex); throw ex; } } public void responseCompleted(final HttpContext context) { try { this.responseConsumer.responseCompleted(context); final T result = this.responseConsumer.getResult(); final Exception ex = this.responseConsumer.getException(); if (ex == null) { this.future.completed(result); } else { this.future.failed(ex); } releaseResources(); } catch (final RuntimeException ex) { failed(ex); throw ex; } } public T getResult() { return this.responseConsumer.getResult(); } public Exception getException() { return this.responseConsumer.getException(); } public HttpContext getContext() { return this.localContext; } public HttpProcessor getHttpProcessor() { return this.httppocessor; } public ConnectionReuseStrategy getConnectionReuseStrategy() { return this.reuseStrategy; } public boolean isDone() { return this.responseConsumer.isDone(); } } ././@LongLink0100644 0000000 0000000 00000000203 12613460517 011633 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/HttpAsyncRequestExecutionHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/HttpAsy0100644 0000000 0000000 00000005107 12613456024 032374 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; /** * {@code HttpAsyncRequestExecutionHandler} represents a callback interface * that combines functionality of {@link HttpAsyncRequestProducer} and * {@link HttpAsyncResponseConsumer} and is capable of handling logically * related series of HTTP request / response exchanges. * * @param the result type of request execution. * @since 4.2 * * @deprecated use {@link HttpAsyncClientExchangeHandler} */ @Deprecated public interface HttpAsyncRequestExecutionHandler extends HttpAsyncRequestProducer, HttpAsyncResponseConsumer { /** * Returns shared {@link HttpContext} instance. * * @return HTTP context */ HttpContext getContext(); /** * Returns {@link HttpProcessor} implementation to be used to process * HTTP request and response messages for protocol compliance. * * @return HTTP protocol processor. */ HttpProcessor getHttpProcessor(); /** * Returns {@link ConnectionReuseStrategy} implementation to be used * to determine whether or not the underlying connection can be kept alive * after a particular HTTP request / response exchange. * * @return connection re-use strategy. */ ConnectionReuseStrategy getConnectionReuseStrategy(); } ././@LongLink0100644 0000000 0000000 00000000176 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/BufferingHttpServiceHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/Bufferi0100644 0000000 0000000 00000016265 12613456024 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.nio.protocol; import java.io.IOException; 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.annotation.Immutable; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.entity.BufferingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParams; 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.HttpRequestHandlerResolver; /** * Service protocol handler implementations that provide compatibility with * the blocking I/O by storing the full content of HTTP messages in memory. * The {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)} * method will fire only when the entire message content has been read into * an in-memory buffer. Please note that request processing take place the * main I/O thread and therefore individual HTTP request handlers should not * block indefinitely. *

* When using this protocol handler {@link org.apache.http.HttpEntity}'s content * can be generated / consumed using standard {@link java.io.InputStream}/ * {@link java.io.OutputStream} classes. *

* IMPORTANT: This protocol handler should be used only when dealing with HTTP * messages that are known to be limited in length. * * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncService} */ @Deprecated @Immutable // provided injected dependencies are immutable public class BufferingHttpServiceHandler implements NHttpServiceHandler { private final AsyncNHttpServiceHandler asyncHandler; private HttpRequestHandlerResolver handlerResolver; public BufferingHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final HttpParams params) { super(); this.asyncHandler = new AsyncNHttpServiceHandler( httpProcessor, responseFactory, connStrategy, allocator, params); this.asyncHandler.setHandlerResolver(new RequestHandlerResolverAdaptor()); } public BufferingHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final HttpParams params) { this(httpProcessor, responseFactory, connStrategy, HeapByteBufferAllocator.INSTANCE, params); } public void setEventListener(final EventListener eventListener) { this.asyncHandler.setEventListener(eventListener); } public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { this.asyncHandler.setExpectationVerifier(expectationVerifier); } public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) { this.handlerResolver = handlerResolver; } public void connected(final NHttpServerConnection conn) { this.asyncHandler.connected(conn); } public void closed(final NHttpServerConnection conn) { this.asyncHandler.closed(conn); } public void requestReceived(final NHttpServerConnection conn) { this.asyncHandler.requestReceived(conn); } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { this.asyncHandler.inputReady(conn, decoder); } public void responseReady(final NHttpServerConnection conn) { this.asyncHandler.responseReady(conn); } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { this.asyncHandler.outputReady(conn, encoder); } public void exception(final NHttpServerConnection conn, final HttpException httpex) { this.asyncHandler.exception(conn, httpex); } public void exception(final NHttpServerConnection conn, final IOException ioex) { this.asyncHandler.exception(conn, ioex); } public void timeout(final NHttpServerConnection conn) { this.asyncHandler.timeout(conn); } class RequestHandlerResolverAdaptor implements NHttpRequestHandlerResolver { public NHttpRequestHandler lookup(final String requestURI) { final HttpRequestHandler handler = handlerResolver.lookup(requestURI); if (handler != null) { return new RequestHandlerAdaptor(handler); } else { return null; } } } static class RequestHandlerAdaptor extends SimpleNHttpRequestHandler { private final HttpRequestHandler requestHandler; public RequestHandlerAdaptor(final HttpRequestHandler requestHandler) { super(); this.requestHandler = requestHandler; } public ConsumingNHttpEntity entityRequest( final HttpEntityEnclosingRequest request, final HttpContext context) throws HttpException, IOException { return new BufferingNHttpEntity( request.getEntity(), HeapByteBufferAllocator.INSTANCE); } @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { this.requestHandler.handle(request, response, context); } } } ././@LongLink0100644 0000000 0000000 00000000177 12613460517 011645 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/ThrottlingHttpServiceHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/Throttl0100644 0000000 0000000 00000065664 12613456024 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.nio.protocol; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.Executor; 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.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.UnsupportedHttpVersionException; import org.apache.http.annotation.ThreadSafe; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.entity.ContentBufferEntity; import org.apache.http.nio.entity.ContentOutputStream; import org.apache.http.nio.params.NIOReactorPNames; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.ContentInputBuffer; import org.apache.http.nio.util.ContentOutputBuffer; import org.apache.http.nio.util.DirectByteBufferAllocator; import org.apache.http.nio.util.SharedInputBuffer; import org.apache.http.nio.util.SharedOutputBuffer; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; 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.HttpRequestHandlerResolver; import org.apache.http.util.Args; import org.apache.http.util.EncodingUtils; import org.apache.http.util.EntityUtils; /** * Service protocol handler implementation that provide compatibility with * the blocking I/O by utilizing shared content buffers and a fairly small pool * of worker threads. The throttling protocol handler allocates input / output * buffers of a constant length upon initialization and controls the rate of * I/O events in order to ensure those content buffers do not ever get * overflown. This helps ensure nearly constant memory footprint for HTTP * connections and avoid the out of memory condition while streaming content * in and out. The {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)} * method will fire immediately when a message is received. The protocol handler * delegate the task of processing requests and generating response content to * an {@link Executor}, which is expected to perform those tasks using * dedicated worker threads in order to avoid blocking the I/O thread. *

* Usually throttling protocol handlers need only a modest number of worker * threads, much fewer than the number of concurrent connections. If the length * of the message is smaller or about the size of the shared content buffer * worker thread will just store content in the buffer and terminate almost * immediately without blocking. The I/O dispatch thread in its turn will take * care of sending out the buffered content asynchronously. The worker thread * will have to block only when processing large messages and the shared buffer * fills up. It is generally advisable to allocate shared buffers of a size of * an average content body for optimal performance. *

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

    *
  • {@link org.apache.http.nio.params.NIOReactorPNames#CONTENT_BUFFER_SIZE}
  • *
  • {@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}
  • *
* * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncService} */ @Deprecated @ThreadSafe // provided injected dependencies are immutable or thread safe public class ThrottlingHttpServiceHandler extends NHttpHandlerBase implements NHttpServiceHandler { protected final HttpResponseFactory responseFactory; protected final Executor executor; protected HttpRequestHandlerResolver handlerResolver; protected HttpExpectationVerifier expectationVerifier; private final int bufsize; public ThrottlingHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final Executor executor, final HttpParams params) { super(httpProcessor, connStrategy, allocator, params); Args.notNull(responseFactory, "Response factory"); Args.notNull(executor, "Executor"); this.responseFactory = responseFactory; this.executor = executor; this.bufsize = this.params.getIntParameter(NIOReactorPNames.CONTENT_BUFFER_SIZE, 20480); } public ThrottlingHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final Executor executor, final HttpParams params) { this(httpProcessor, responseFactory, connStrategy, DirectByteBufferAllocator.INSTANCE, executor, params); } public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) { this.handlerResolver = handlerResolver; } public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; } public void connected(final NHttpServerConnection conn) { final HttpContext context = conn.getContext(); final ServerConnState connState = new ServerConnState(this.bufsize, conn, allocator); context.setAttribute(CONN_STATE, connState); if (this.eventListener != null) { this.eventListener.connectionOpen(conn); } } public void closed(final NHttpServerConnection conn) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); if (connState != null) { synchronized (connState) { connState.close(); connState.notifyAll(); } } if (this.eventListener != null) { this.eventListener.connectionClosed(conn); } } public void exception(final NHttpServerConnection conn, final HttpException httpex) { if (conn.isResponseSubmitted()) { if (eventListener != null) { eventListener.fatalProtocolException(httpex, conn); } return; } final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); try { final HttpResponse response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); response.setEntity(null); this.httpProcessor.process(response, context); synchronized (connState) { connState.setResponse(response); // Response is ready to be committed conn.requestOutput(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (eventListener != null) { eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (eventListener != null) { eventListener.fatalProtocolException(ex, conn); } } } public void exception(final NHttpServerConnection conn, final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } public void timeout(final NHttpServerConnection conn) { handleTimeout(conn); } public void requestReceived(final NHttpServerConnection conn) { final HttpContext context = conn.getContext(); final HttpRequest request = conn.getHttpRequest(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); synchronized (connState) { boolean contentExpected = false; if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { contentExpected = true; } } if (!contentExpected) { conn.suspendInput(); } this.executor.execute(new Runnable() { public void run() { try { handleRequest(request, connState, conn); } catch (final IOException ex) { shutdownConnection(conn, ex); if (eventListener != null) { eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { shutdownConnection(conn, ex); if (eventListener != null) { eventListener.fatalProtocolException(ex, conn); } } } }); connState.notifyAll(); } } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); try { synchronized (connState) { final ContentInputBuffer buffer = connState.getInbuffer(); buffer.consumeContent(decoder); if (decoder.isCompleted()) { connState.setInputState(ServerConnState.REQUEST_BODY_DONE); } else { connState.setInputState(ServerConnState.REQUEST_BODY_STREAM); } connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } public void responseReady(final NHttpServerConnection conn) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); try { synchronized (connState) { if (connState.isExpectationFailed()) { // Server expection failed // Well-behaved client will not be sending // a request body conn.resetInput(); connState.setExpectationFailed(false); } final HttpResponse response = connState.getResponse(); if (connState.getOutputState() == ServerConnState.READY && response != null && !conn.isResponseSubmitted()) { conn.submitResponse(response); final int statusCode = response.getStatusLine().getStatusCode(); final HttpEntity entity = response.getEntity(); if (statusCode >= 200 && entity == null) { connState.setOutputState(ServerConnState.RESPONSE_DONE); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } } else { connState.setOutputState(ServerConnState.RESPONSE_SENT); } } connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (eventListener != null) { eventListener.fatalIOException(ex, conn); } } catch (final HttpException ex) { closeConnection(conn, ex); if (eventListener != null) { eventListener.fatalProtocolException(ex, conn); } } } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); try { synchronized (connState) { final HttpResponse response = connState.getResponse(); final ContentOutputBuffer buffer = connState.getOutbuffer(); buffer.produceContent(encoder); if (encoder.isCompleted()) { connState.setOutputState(ServerConnState.RESPONSE_BODY_DONE); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } } else { connState.setOutputState(ServerConnState.RESPONSE_BODY_STREAM); } connState.notifyAll(); } } catch (final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } private 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); } final byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage()); final ByteArrayEntity entity = new ByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); } private void handleRequest( final HttpRequest request, final ServerConnState connState, final NHttpServerConnection conn) throws HttpException, IOException { final HttpContext context = conn.getContext(); // Block until previous request is fully processed and // the worker thread no longer holds the shared buffer synchronized (connState) { try { for (;;) { final int currentState = connState.getOutputState(); if (currentState == ServerConnState.READY) { break; } if (currentState == ServerConnState.SHUTDOWN) { return; } connState.wait(); } } catch (final InterruptedException ex) { connState.shutdown(); return; } connState.setInputState(ServerConnState.REQUEST_RECEIVED); connState.setRequest(request); } request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } HttpResponse response = null; if (request instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest eeRequest = (HttpEntityEnclosingRequest) request; if (eeRequest.expectContinue()) { response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); 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); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(ex, response); } } synchronized (connState) { if (response.getStatusLine().getStatusCode() < 200) { // Send 1xx response indicating the server expections // have been met connState.setResponse(response); conn.requestOutput(); // Block until 1xx response is sent to the client try { for (;;) { final int currentState = connState.getOutputState(); if (currentState == ServerConnState.RESPONSE_SENT) { break; } if (currentState == ServerConnState.SHUTDOWN) { return; } connState.wait(); } } catch (final InterruptedException ex) { connState.shutdown(); return; } connState.resetOutput(); response = null; } else { // Discard request entity eeRequest.setEntity(null); conn.suspendInput(); connState.setExpectationFailed(true); } } } // Create a wrapper entity instead of the original one if (eeRequest.getEntity() != null) { eeRequest.setEntity(new ContentBufferEntity( eeRequest.getEntity(), connState.getInbuffer())); } } if (response == null) { response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_OK, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); context.setAttribute(ExecutionContext.HTTP_RESPONSE, response); try { this.httpProcessor.process(request, context); HttpRequestHandler handler = null; if (this.handlerResolver != null) { final String requestURI = request.getRequestLine().getUri(); handler = this.handlerResolver.lookup(requestURI); } if (handler != null) { handler.handle(request, response, context); } else { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } } catch (final HttpException ex) { response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(ex, response); } } if (request instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest eeRequest = (HttpEntityEnclosingRequest) request; final HttpEntity entity = eeRequest.getEntity(); EntityUtils.consume(entity); } // It should be safe to reset the input state at this point connState.resetInput(); this.httpProcessor.process(response, context); if (!canResponseHaveBody(request, response)) { response.setEntity(null); } connState.setResponse(response); // Response is ready to be committed conn.requestOutput(); if (response.getEntity() != null) { final ContentOutputBuffer buffer = connState.getOutbuffer(); final OutputStream outstream = new ContentOutputStream(buffer); final HttpEntity entity = response.getEntity(); entity.writeTo(outstream); outstream.flush(); outstream.close(); } synchronized (connState) { try { for (;;) { final int currentState = connState.getOutputState(); if (currentState == ServerConnState.RESPONSE_DONE) { break; } if (currentState == ServerConnState.SHUTDOWN) { return; } connState.wait(); } } catch (final InterruptedException ex) { connState.shutdown(); return; } connState.resetOutput(); conn.requestInput(); connState.notifyAll(); } } @Override protected void shutdownConnection(final NHttpConnection conn, final Throwable cause) { final HttpContext context = conn.getContext(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); super.shutdownConnection(conn, cause); if (connState != null) { connState.shutdown(); } } static class ServerConnState { public static final int SHUTDOWN = -1; public static final int READY = 0; public static final int REQUEST_RECEIVED = 1; public static final int REQUEST_BODY_STREAM = 2; public static final int REQUEST_BODY_DONE = 4; public static final int RESPONSE_SENT = 8; public static final int RESPONSE_BODY_STREAM = 16; public static final int RESPONSE_BODY_DONE = 32; public static final int RESPONSE_DONE = 32; private final SharedInputBuffer inbuffer; private final SharedOutputBuffer outbuffer; private volatile int inputState; private volatile int outputState; private volatile HttpRequest request; private volatile HttpResponse response; private volatile boolean expectationFailure; public ServerConnState( final int bufsize, final IOControl ioControl, final ByteBufferAllocator allocator) { super(); this.inbuffer = new SharedInputBuffer(bufsize, ioControl, allocator); this.outbuffer = new SharedOutputBuffer(bufsize, ioControl, allocator); this.inputState = READY; this.outputState = READY; } public ContentInputBuffer getInbuffer() { return this.inbuffer; } public ContentOutputBuffer getOutbuffer() { return this.outbuffer; } public int getInputState() { return this.inputState; } public void setInputState(final int inputState) { this.inputState = inputState; } public int getOutputState() { return this.outputState; } public void setOutputState(final int outputState) { this.outputState = outputState; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public boolean isExpectationFailed() { return expectationFailure; } public void setExpectationFailed(final boolean b) { this.expectationFailure = b; } public void close() { this.inbuffer.close(); this.outbuffer.close(); this.inputState = SHUTDOWN; this.outputState = SHUTDOWN; } public void shutdown() { this.inbuffer.shutdown(); this.outbuffer.shutdown(); this.inputState = SHUTDOWN; this.outputState = SHUTDOWN; } public void resetInput() { this.inbuffer.reset(); this.request = null; this.inputState = READY; } public void resetOutput() { this.outbuffer.reset(); this.response = null; this.outputState = READY; this.expectationFailure = false; } } } ././@LongLink0100644 0000000 0000000 00000000174 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/SimpleNHttpRequestHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/SimpleN0100644 0000000 0000000 00000004445 12613456024 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.nio.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.annotation.Immutable; import org.apache.http.protocol.HttpContext; /** * A simple implementation of {@link NHttpRequestHandler} that abstracts away * the need to use {@link NHttpResponseTrigger}. Implementations need only to * implement {@link #handle(HttpRequest, HttpResponse, HttpContext)}. * * @since 4.0 * * @deprecated (4.2) use {@link BasicAsyncRequestHandler} */ @Deprecated @Immutable public abstract class SimpleNHttpRequestHandler implements NHttpRequestHandler { public final void handle( final HttpRequest request, final HttpResponse response, final NHttpResponseTrigger trigger, final HttpContext context) throws HttpException, IOException { handle(request, response, context); trigger.submitResponse(response); } public abstract void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException; } ././@LongLink0100644 0000000 0000000 00000000166 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRequestHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRe0100644 0000000 0000000 00000010044 12613456024 032320 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.protocol.HttpContext; /** * NHttpRequestHandler 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 * * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncRequestHandler} */ @Deprecated public interface NHttpRequestHandler { /** * Triggered when a request is received with an entity. This method should * return a {@link ConsumingNHttpEntity} that will be used to consume the * entity. {@code null} is a valid response value, and will indicate * that the entity should be silently ignored. *

* After the entity is fully consumed, * {@link #handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)} * is called to notify a full request & entity are ready to be processed. * * @param request the entity enclosing request. * @param context the execution context. * @return non-blocking HTTP entity. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ ConsumingNHttpEntity entityRequest(HttpEntityEnclosingRequest request, HttpContext context) throws HttpException, IOException; /** * Initiates processing of the request. This method does not have to submit * a response immediately. It can 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. The worker * thread in its turn can use the instance of {@link NHttpResponseTrigger} * passed as a parameter to submit a response as at a later point of time * once content of the response becomes available. * * @param request the HTTP request. * @param response the HTTP response. * @param trigger the response trigger. * @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, NHttpResponseTrigger trigger, HttpContext context) throws HttpException, IOException; } ././@LongLink0100644 0000000 0000000 00000000162 12613460517 011637 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NullNHttpEntity.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NullNHt0100644 0000000 0000000 00000005140 12613456024 032321 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.ConsumingNHttpEntity; /** * @deprecated (4.2) */ @Deprecated class NullNHttpEntity extends HttpEntityWrapper implements ConsumingNHttpEntity { private final ByteBuffer buffer; public NullNHttpEntity(final HttpEntity httpEntity) { super(httpEntity); this.buffer = ByteBuffer.allocate(2048); } @Override public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } @Override public boolean isStreaming() { return true; } @Override public void writeTo(final OutputStream out) throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { int lastRead; do { buffer.clear(); lastRead = decoder.read(buffer); } while (lastRead > 0); } public void finish() { } } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpResponseTrigger.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRe0100644 0000000 0000000 00000004760 12613456024 032330 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpResponse; /** * Callback interface to submit HTTP responses asynchronously. *

* The {@link NHttpRequestHandler#handle(org.apache.http.HttpRequest, HttpResponse, NHttpResponseTrigger, org.apache.http.protocol.HttpContext)} * method does not have to submit a response immediately. It can 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. The worker thread in its turn can use the instance of * {@link NHttpResponseTrigger} passed as a parameter to submit a response as at * a later point of time once the response becomes available. * * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncExchange} */ @Deprecated public interface NHttpResponseTrigger { /** * Submits a response to be sent back to the client as a result of * processing of the request. */ void submitResponse(HttpResponse response); /** * Reports a protocol exception thrown while processing the request. */ void handleException(HttpException ex); /** * Report an IOException thrown while processing the request. */ void handleException(IOException ex); } ././@LongLink0100644 0000000 0000000 00000000177 12613460517 011645 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRequestExecutionHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/NHttpRe0100644 0000000 0000000 00000011567 12613456024 032333 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.protocol.HttpContext; /** * HTTP request execution handler can be used by client-side protocol handlers * to trigger the submission of a new HTTP request and the processing of an HTTP * response. When a new response entity is available for consumption, * {@link #responseEntity(HttpResponse, HttpContext)} is called. * After the {@link ConsumingNHttpEntity} consumes the response body, * {@link #handleResponse(HttpResponse, HttpContext)} is notified that the * response is fully read. * * @since 4.0 * * @deprecated (4.2) use {@link HttpAsyncRequestExecutor} and {@link HttpAsyncRequester} */ @Deprecated public interface NHttpRequestExecutionHandler { /** * Triggered when a new connection has been established and the * HTTP context needs to be initialized. * *

The attachment object is the same object which was passed * to the connecting I/O reactor when the connection request was * made. The attachment may optionally contain some state information * required in order to correctly initalize the HTTP context. * * @see org.apache.http.nio.reactor.ConnectingIOReactor#connect * * @param context the actual HTTP context * @param attachment the object passed to the connecting I/O reactor * upon the request for a new connection. */ void initalizeContext(HttpContext context, Object attachment); /** * Triggered when the underlying connection is ready to send a new * HTTP request to the target host. This method may return * {@code null} if the client is not yet ready to send a * request. In this case the connection will remain open and * can be activated at a later point. *

* If the request has an entity, the entity must be an * instance of {@link org.apache.http.nio.entity.ProducingNHttpEntity}. * * @param context the actual HTTP context * @return an HTTP request to be sent or {@code null} if no * request needs to be sent */ HttpRequest submitRequest(HttpContext context); /** * Triggered when a response is received with an entity. This method should * return a {@link ConsumingNHttpEntity} that will be used to consume the * entity. {@code null} is a valid response value, and will indicate * that the entity should be silently ignored. *

* After the entity is fully consumed, * {@link NHttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)} * is called to notify a full response & entity are ready to be processed. * * @param response * The response containing the existing entity. * @param context * the actual HTTP context * @return An entity that will asynchronously consume the response's content * body. */ ConsumingNHttpEntity responseEntity(HttpResponse response, HttpContext context) throws IOException; /** * Triggered when an HTTP response is ready to be processed. * * @param response * the HTTP response to be processed * @param context * the actual HTTP context */ void handleResponse(HttpResponse response, HttpContext context) throws IOException; /** * Triggered when the connection is terminated. This event can be used * to release objects stored in the context or perform some other kind * of cleanup. * * @param context the actual HTTP context */ void finalizeContext(HttpContext context); } ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/EventListener.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/protocol/EventLi0100644 0000000 0000000 00000005015 12613456024 032344 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.protocol; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.nio.NHttpConnection; /** * Event listener used by the HTTP protocol layer to report fatal exceptions * and events that may need to be logged using a logging toolkit. * * @since 4.0 * * @deprecated (4.2) do not use */ @Deprecated public interface EventListener { /** * Triggered when an I/O error caused a connection to be terminated. * * @param ex the I/O exception. * @param conn the connection. */ void fatalIOException(IOException ex, NHttpConnection conn); /** * Triggered when an HTTP protocol error caused a connection to be * terminated. * * @param ex the protocol exception. * @param conn the connection. */ void fatalProtocolException(HttpException ex, NHttpConnection conn); /** * Triggered when a new connection has been established. * * @param conn the connection. */ void connectionOpen(NHttpConnection conn); /** * Triggered when a connection has been terminated. * * @param conn the connection. */ void connectionClosed(NHttpConnection conn); /** * Triggered when a connection has timed out. * * @param conn the connection. */ void connectionTimeout(NHttpConnection conn); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/0040755 0000000 0000000 00000000000 12613456024 030530 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000175 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/ConsumingNHttpEntityTemplate.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/Consuming0100644 0000000 0000000 00000005667 12613456024 032430 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; /** * A {@link ConsumingNHttpEntity} that forwards available content to a * {@link ContentListener}. * * @since 4.0 * * @deprecated use (4.2) * {@link org.apache.http.nio.protocol.BasicAsyncRequestProducer} * or {@link org.apache.http.nio.protocol.BasicAsyncResponseProducer} */ @Deprecated public class ConsumingNHttpEntityTemplate extends HttpEntityWrapper implements ConsumingNHttpEntity { private final ContentListener contentListener; public ConsumingNHttpEntityTemplate( final HttpEntity httpEntity, final ContentListener contentListener) { super(httpEntity); this.contentListener = contentListener; } public ContentListener getContentListener() { return contentListener; } @Override public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } @Override public boolean isStreaming() { return true; } @Override public void writeTo(final OutputStream out) throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { this.contentListener.contentAvailable(decoder, ioctrl); } public void finish() { this.contentListener.finished(); } } ././@LongLink0100644 0000000 0000000 00000000163 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/NHttpEntityWrapper.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/NHttpEnti0100644 0000000 0000000 00000006640 12613456024 032333 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.apache.http.HttpEntity; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; /** * {@link ProducingNHttpEntity} compatibility adaptor for blocking HTTP * entities. * * @since 4.0 * * @deprecated (4.2) use {@link EntityAsyncContentProducer} */ @NotThreadSafe @Deprecated public class NHttpEntityWrapper extends HttpEntityWrapper implements ProducingNHttpEntity { private final ReadableByteChannel channel; private final ByteBuffer buffer; public NHttpEntityWrapper(final HttpEntity httpEntity) throws IOException { super(httpEntity); this.channel = Channels.newChannel(httpEntity.getContent()); this.buffer = ByteBuffer.allocate(4096); } /** * This method throws {@link UnsupportedOperationException}. */ @Override public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } @Override public boolean isStreaming() { return true; } /** * This method throws {@link UnsupportedOperationException}. */ @Override public void writeTo(final OutputStream out) throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { final int i = this.channel.read(this.buffer); this.buffer.flip(); encoder.write(this.buffer); final boolean buffering = this.buffer.hasRemaining(); this.buffer.compact(); if (i == -1 && !buffering) { encoder.complete(); this.channel.close(); } } public void finish() { try { this.channel.close(); } catch (final IOException ignore) { } } } ././@LongLink0100644 0000000 0000000 00000000165 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/BufferingNHttpEntity.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/Buffering0100644 0000000 0000000 00000007723 12613456024 032370 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; 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.entity.HttpEntityWrapper; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.SimpleInputBuffer; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * A {@link ConsumingNHttpEntity} that consumes content into a buffer. The * content can be retrieved as an InputStream via * {@link HttpEntity#getContent()}, or written to an output stream via * {@link HttpEntity#writeTo(OutputStream)}. * * @since 4.0 * * @deprecated use (4.2) * {@link org.apache.http.nio.protocol.BasicAsyncRequestProducer} * or {@link org.apache.http.nio.protocol.BasicAsyncResponseProducer} */ @NotThreadSafe @Deprecated public class BufferingNHttpEntity extends HttpEntityWrapper implements ConsumingNHttpEntity { private final static int BUFFER_SIZE = 2048; private final SimpleInputBuffer buffer; private boolean finished; private boolean consumed; public BufferingNHttpEntity( final HttpEntity httpEntity, final ByteBufferAllocator allocator) { super(httpEntity); this.buffer = new SimpleInputBuffer(BUFFER_SIZE, allocator); } public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { this.buffer.consumeContent(decoder); if (decoder.isCompleted()) { this.finished = true; } } public void finish() { this.finished = true; } /** * Obtains entity's content as {@link InputStream}. * * @throws IllegalStateException if content of the entity has not been * fully received or has already been consumed. */ @Override public InputStream getContent() throws IOException { Asserts.check(this.finished, "Entity content has not been fully received"); Asserts.check(!this.consumed, "Entity content has been consumed"); this.consumed = true; return new ContentInputStream(this.buffer); } @Override public boolean isRepeatable() { return false; } @Override public boolean isStreaming() { return true; } @Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); final InputStream instream = getContent(); final byte[] buff = new byte[BUFFER_SIZE]; int l; // consume until EOF while ((l = instream.read(buff)) != -1) { outstream.write(buff, 0, l); } } } ././@LongLink0100644 0000000 0000000 00000000164 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/SkipContentListener.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/SkipConte0100644 0000000 0000000 00000004227 12613456024 032354 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.util.Args; /** * A simple {@link ContentListener} that reads and ignores all content. * * @since 4.0 * * @deprecated (4.2) */ @Deprecated public class SkipContentListener implements ContentListener { private final ByteBuffer buffer; public SkipContentListener(final ByteBufferAllocator allocator) { super(); Args.notNull(allocator, "ByteBuffer allocator"); this.buffer = allocator.allocate(2048); } public void contentAvailable( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { int lastRead; do { buffer.clear(); lastRead = decoder.read(buffer); } while (lastRead > 0); } public void finished() { } } ././@LongLink0100644 0000000 0000000 00000000160 12613460517 011635 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/ContentListener.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/nio/entity/ContentLi0100644 0000000 0000000 00000003606 12613456024 032354 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.nio.entity; import java.io.IOException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; /** * A listener for available data on a non-blocking {@link ConsumingNHttpEntity}. * * @since 4.0 * * @deprecated (4.2) */ @Deprecated public interface ContentListener { /** * Notification that content is available to be read from the decoder. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. */ void contentAvailable(ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Notification that any resources allocated for reading can be released. */ void finished(); } httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/0040755 0000000 0000000 00000000000 12613456024 027370 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/0040755 0000000 0000000 00000000000 12613456024 030155 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/SSLClientIOEventDispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/SSLClientIO0100644 0000000 0000000 00000022270 12613456024 032130 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import org.apache.http.HttpResponseFactory; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.reactor.SSLIOSession; import org.apache.http.impl.nio.reactor.SSLIOSessionHandler; import org.apache.http.impl.nio.reactor.SSLMode; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpClientIOTarget; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.util.Args; /** * Default implementation of {@link IOEventDispatch} interface for SSL * (encrypted) client-side HTTP connections. * * @since 4.0 * * @deprecated (4.2) use {@link org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch} */ @Deprecated public class SSLClientIOEventDispatch implements IOEventDispatch { private static final String SSL_SESSION = "SSL_SESSION"; protected final NHttpClientHandler handler; protected final SSLContext sslcontext; protected final SSLIOSessionHandler sslHandler; protected final HttpParams params; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the client protocol handler. * @param sslcontext the SSL context. * @param sslHandler the SSL handler. * @param params HTTP parameters. */ public SSLClientIOEventDispatch( final NHttpClientHandler handler, final SSLContext sslcontext, final SSLIOSessionHandler sslHandler, final HttpParams params) { super(); Args.notNull(handler, "HTTP client handler"); Args.notNull(sslcontext, "SSL context"); Args.notNull(params, "HTTP parameters"); this.handler = handler; this.params = params; this.sslcontext = sslcontext; this.sslHandler = sslHandler; } /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the client protocol handler. * @param sslcontext the SSL context. * @param params HTTP parameters. */ public SSLClientIOEventDispatch( final NHttpClientHandler handler, final SSLContext sslcontext, final HttpParams params) { this(handler, sslcontext, null, params); } /** * Creates an instance of {@link HeapByteBufferAllocator} to be used * by HTTP connections for allocating {@link java.nio.ByteBuffer} objects. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link ByteBufferAllocator} interface. * * @return byte buffer allocator. */ protected ByteBufferAllocator createByteBufferAllocator() { return HeapByteBufferAllocator.INSTANCE; } /** * Creates an instance of {@link DefaultHttpResponseFactory} to be used * by HTTP connections for creating {@link org.apache.http.HttpResponse} * objects. *

* 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 DefaultNHttpClientConnection} based on the * given SSL {@link IOSession}. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpClientIOTarget} interface. * * @param session the underlying SSL I/O session. * * @return newly created HTTP connection. */ protected NHttpClientIOTarget createConnection(final IOSession session) { return new DefaultNHttpClientConnection( session, createHttpResponseFactory(), createByteBufferAllocator(), this.params); } /** * Creates an instance of {@link SSLIOSession} decorating the given * {@link IOSession}. *

* This method can be overridden in a super class in order to provide * a different implementation of SSL I/O session. * * @param session the underlying I/O session. * @param sslcontext the SSL context. * @param sslHandler the SSL handler. * @return newly created SSL I/O session. */ protected SSLIOSession createSSLIOSession( final IOSession session, final SSLContext sslcontext, final SSLIOSessionHandler sslHandler) { return new SSLIOSession(session, sslcontext, sslHandler); } public void connected(final IOSession session) { final SSLIOSession sslSession = createSSLIOSession( session, this.sslcontext, this.sslHandler); final NHttpClientIOTarget conn = createConnection( sslSession); session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); session.setAttribute(SSL_SESSION, sslSession); final Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY); this.handler.connected(conn, attachment); try { sslSession.bind(SSLMode.CLIENT, this.params); } catch (final SSLException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void disconnected(final IOSession session) { final NHttpClientIOTarget conn = (NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); if (conn != null) { this.handler.closed(conn); } } public void inputReady(final IOSession session) { final NHttpClientIOTarget conn = (NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); final SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); try { if (sslSession.isAppInputReady()) { conn.consumeInput(this.handler); } sslSession.inboundTransport(); } catch (final IOException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void outputReady(final IOSession session) { final NHttpClientIOTarget conn = (NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); final SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); try { if (sslSession.isAppOutputReady()) { conn.produceOutput(this.handler); } sslSession.outboundTransport(); } catch (final IOException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void timeout(final IOSession session) { final NHttpClientIOTarget conn = (NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); final SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); this.handler.timeout(conn); synchronized (sslSession) { if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) { // The session failed to terminate cleanly sslSession.shutdown(); } } } } ././@LongLink0100644 0000000 0000000 00000000173 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/DefaultClientIOEventDispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/DefaultClie0100644 0000000 0000000 00000013060 12613456024 032256 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import org.apache.http.HttpResponseFactory; import org.apache.http.annotation.Immutable; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.reactor.AbstractIODispatch; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpClientIOTarget; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default implementation of {@link org.apache.http.nio.reactor.IOEventDispatch} * interface for plain (unencrypted) client-side HTTP connections. * * @since 4.0 * * @deprecated (4.2) use {@link DefaultHttpClientIODispatch} */ @Deprecated @Immutable // provided injected dependencies are immutable public class DefaultClientIOEventDispatch extends AbstractIODispatch { protected final NHttpClientHandler handler; protected final ByteBufferAllocator allocator; protected final HttpParams params; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler. * * @param handler the client protocol handler. * @param params HTTP parameters. */ public DefaultClientIOEventDispatch( final NHttpClientHandler handler, final HttpParams params) { super(); Args.notNull(handler, "HTTP client handler"); Args.notNull(params, "HTTP parameters"); this.allocator = createByteBufferAllocator(); this.handler = handler; this.params = params; } /** * Creates an instance of {@link HeapByteBufferAllocator} to be used * by HTTP connections for allocating {@link java.nio.ByteBuffer} objects. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link ByteBufferAllocator} interface. * * @return byte buffer allocator. */ protected ByteBufferAllocator createByteBufferAllocator() { return HeapByteBufferAllocator.INSTANCE; } /** * Creates an instance of {@link DefaultHttpResponseFactory} to be used * by HTTP connections for creating {@link org.apache.http.HttpResponse} * objects. *

* 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 DefaultNHttpClientConnection} based on the * given {@link IOSession}. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpClientIOTarget} interface. * * @param session the underlying I/O session. * * @return newly created HTTP connection. */ @Override protected NHttpClientIOTarget createConnection(final IOSession session) { return new DefaultNHttpClientConnection( session, createHttpResponseFactory(), this.allocator, this.params); } @Override protected void onConnected(final NHttpClientIOTarget conn) { final int timeout = HttpConnectionParams.getSoTimeout(this.params); conn.setSocketTimeout(timeout); final Object attachment = conn.getContext().getAttribute(IOSession.ATTACHMENT_KEY); this.handler.connected(conn, attachment); } @Override protected void onClosed(final NHttpClientIOTarget conn) { this.handler.closed(conn); } @Override protected void onException(final NHttpClientIOTarget conn, final IOException ex) { this.handler.exception(conn, ex); } @Override protected void onInputReady(final NHttpClientIOTarget conn) { conn.consumeInput(this.handler); } @Override protected void onOutputReady(final NHttpClientIOTarget conn) { conn.produceOutput(this.handler); } @Override protected void onTimeout(final NHttpClientIOTarget conn) { this.handler.timeout(conn); } } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/SSLServerIOEventDispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/SSLServerIO0100644 0000000 0000000 00000022122 12613456024 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.impl.nio; import java.io.IOException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import org.apache.http.HttpRequestFactory; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.impl.nio.reactor.SSLIOSession; import org.apache.http.impl.nio.reactor.SSLIOSessionHandler; import org.apache.http.impl.nio.reactor.SSLMode; import org.apache.http.nio.NHttpServerIOTarget; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.util.Args; /** * Default implementation of {@link IOEventDispatch} interface for SSL * (encrypted) server-side HTTP connections. * * @since 4.0 * * @deprecated (4.2) use {@link org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch} */ @Deprecated public class SSLServerIOEventDispatch implements IOEventDispatch { private static final String SSL_SESSION = "SSL_SESSION"; protected final NHttpServiceHandler handler; protected final SSLContext sslcontext; protected final SSLIOSessionHandler sslHandler; protected final HttpParams params; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the server protocol handler. * @param sslcontext the SSL context. * @param sslHandler the SSL handler. * @param params HTTP parameters. */ public SSLServerIOEventDispatch( final NHttpServiceHandler handler, final SSLContext sslcontext, final SSLIOSessionHandler sslHandler, final HttpParams params) { super(); Args.notNull(handler, "HTTP service handler"); Args.notNull(sslcontext, "SSL context"); Args.notNull(params, "HTTP parameters"); this.handler = handler; this.params = params; this.sslcontext = sslcontext; this.sslHandler = sslHandler; } /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the server protocol handler. * @param sslcontext the SSL context. * @param params HTTP parameters. */ public SSLServerIOEventDispatch( final NHttpServiceHandler handler, final SSLContext sslcontext, final HttpParams params) { this(handler, sslcontext, null, params); } /** * Creates an instance of {@link HeapByteBufferAllocator} to be used * by HTTP connections for allocating {@link java.nio.ByteBuffer} objects. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link ByteBufferAllocator} interface. * * @return byte buffer allocator. */ protected ByteBufferAllocator createByteBufferAllocator() { return HeapByteBufferAllocator.INSTANCE; } /** * Creates an instance of {@link DefaultHttpRequestFactory} to be used * by HTTP connections for creating {@link org.apache.http.HttpRequest} * objects. *

* 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 DefaultNHttpServerConnection} based on the * given {@link IOSession}. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpServerIOTarget} interface. * * @param session the underlying SSL I/O session. * * @return newly created HTTP connection. */ protected NHttpServerIOTarget createConnection(final IOSession session) { return new DefaultNHttpServerConnection( session, createHttpRequestFactory(), createByteBufferAllocator(), this.params); } /** * Creates an instance of {@link SSLIOSession} decorating the given * {@link IOSession}. *

* This method can be overridden in a super class in order to provide * a different implementation of SSL I/O session. * * @param session the underlying I/O session. * @param sslcontext the SSL context. * @param sslHandler the SSL handler. * @return newly created SSL I/O session. */ protected SSLIOSession createSSLIOSession( final IOSession session, final SSLContext sslcontext, final SSLIOSessionHandler sslHandler) { return new SSLIOSession(session, sslcontext, sslHandler); } public void connected(final IOSession session) { final SSLIOSession sslSession = createSSLIOSession( session, this.sslcontext, this.sslHandler); final NHttpServerIOTarget conn = createConnection( sslSession); session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); session.setAttribute(SSL_SESSION, sslSession); this.handler.connected(conn); try { sslSession.bind(SSLMode.SERVER, this.params); } catch (final SSLException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void disconnected(final IOSession session) { final NHttpServerIOTarget conn = (NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); if (conn != null) { this.handler.closed(conn); } } public void inputReady(final IOSession session) { final NHttpServerIOTarget conn = (NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); final SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); try { if (sslSession.isAppInputReady()) { conn.consumeInput(this.handler); } sslSession.inboundTransport(); } catch (final IOException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void outputReady(final IOSession session) { final NHttpServerIOTarget conn = (NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); final SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); try { if (sslSession.isAppOutputReady()) { conn.produceOutput(this.handler); } sslSession.outboundTransport(); } catch (final IOException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void timeout(final IOSession session) { final NHttpServerIOTarget conn = (NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); final SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); this.handler.timeout(conn); synchronized (sslSession) { if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) { // The session failed to cleanly terminate sslSession.shutdown(); } } } } ././@LongLink0100644 0000000 0000000 00000000173 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/DefaultServerIOEventDispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/DefaultServ0100644 0000000 0000000 00000012671 12613456024 032330 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio; import java.io.IOException; import org.apache.http.HttpRequestFactory; import org.apache.http.annotation.Immutable; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.impl.nio.reactor.AbstractIODispatch; import org.apache.http.nio.NHttpServerIOTarget; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default implementation of {@link org.apache.http.nio.reactor.IOEventDispatch} * interface for plain (unencrypted) server-side HTTP connections. * * @since 4.0 * * @deprecated (4.2) use {@link DefaultHttpServerIODispatch} */ @Deprecated @Immutable // provided injected dependencies are immutable public class DefaultServerIOEventDispatch extends AbstractIODispatch { protected final ByteBufferAllocator allocator; protected final NHttpServiceHandler handler; protected final HttpParams params; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler. * * @param handler the server protocol handler. * @param params HTTP parameters. */ public DefaultServerIOEventDispatch( final NHttpServiceHandler handler, final HttpParams params) { super(); Args.notNull(handler, "HTTP service handler"); Args.notNull(params, "HTTP parameters"); this.allocator = createByteBufferAllocator(); this.handler = handler; this.params = params; } /** * Creates an instance of {@link HeapByteBufferAllocator} to be used * by HTTP connections for allocating {@link java.nio.ByteBuffer} objects. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link ByteBufferAllocator} interface. * * @return byte buffer allocator. */ protected ByteBufferAllocator createByteBufferAllocator() { return HeapByteBufferAllocator.INSTANCE; } /** * Creates an instance of {@link DefaultHttpRequestFactory} to be used * by HTTP connections for creating {@link org.apache.http.HttpRequest} * objects. *

* 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 DefaultNHttpServerConnection} based on the * given {@link IOSession}. *

* This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpServerIOTarget} interface. * * @param session the underlying I/O session. * * @return newly created HTTP connection. */ @Override protected NHttpServerIOTarget createConnection(final IOSession session) { return new DefaultNHttpServerConnection( session, createHttpRequestFactory(), this.allocator, this.params); } @Override protected void onConnected(final NHttpServerIOTarget conn) { final int timeout = HttpConnectionParams.getSoTimeout(this.params); conn.setSocketTimeout(timeout); this.handler.connected(conn); } @Override protected void onClosed(final NHttpServerIOTarget conn) { this.handler.closed(conn); } @Override protected void onException(final NHttpServerIOTarget conn, final IOException ex) { this.handler.exception(conn, ex); } @Override protected void onInputReady(final NHttpServerIOTarget conn) { conn.consumeInput(this.handler); } @Override protected void onOutputReady(final NHttpServerIOTarget conn) { conn.produceOutput(this.handler); } @Override protected void onTimeout(final NHttpServerIOTarget conn) { this.handler.timeout(conn); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/0040755 0000000 0000000 00000000000 12613456024 031415 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000170 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/HttpResponseParser.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/Http0100644 0000000 0000000 00000005757 12613456024 032272 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.HttpResponseFactory; import org.apache.http.ParseException; import org.apache.http.StatusLine; import org.apache.http.message.LineParser; import org.apache.http.message.ParserCursor; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; /** * Default {@link org.apache.http.nio.NHttpMessageParser} implementation * for {@link org.apache.http.HttpResponse}s. *

* 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.1) use {@link DefaultHttpResponseParser} */ @SuppressWarnings("rawtypes") @Deprecated public class HttpResponseParser extends AbstractMessageParser { private final HttpResponseFactory responseFactory; public HttpResponseParser( final SessionInputBuffer buffer, final LineParser parser, final HttpResponseFactory responseFactory, final HttpParams params) { super(buffer, parser, params); Args.notNull(responseFactory, "Response factory"); this.responseFactory = responseFactory; } @Override protected HttpMessage createMessage(final CharArrayBuffer buffer) throws HttpException, ParseException { final ParserCursor cursor = new ParserCursor(0, buffer.length()); final StatusLine statusline = lineParser.parseStatusLine(buffer, cursor); return this.responseFactory.newHttpResponse(statusline, null); } } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/HttpRequestWriter.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/Http0100644 0000000 0000000 00000004444 12613456024 032262 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import org.apache.http.HttpMessage; import org.apache.http.HttpRequest; import org.apache.http.message.LineFormatter; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.CharArrayBuffer; /** * Default {@link org.apache.http.nio.NHttpMessageWriter} implementation * for {@link HttpRequest}s. * * @since 4.0 * * @deprecated (4.1) use {@link DefaultHttpRequestWriter} */ @SuppressWarnings("rawtypes") @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 HttpMessage message) throws IOException { final CharArrayBuffer buffer = lineFormatter.formatRequestLine (this.lineBuf, ((HttpRequest) message).getRequestLine()); this.sessionBuffer.writeLine(buffer); } } ././@LongLink0100644 0000000 0000000 00000000170 12613460517 011636 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/HttpResponseWriter.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/Http0100644 0000000 0000000 00000004452 12613456024 032261 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.codecs; import java.io.IOException; import org.apache.http.HttpMessage; import org.apache.http.HttpResponse; import org.apache.http.message.LineFormatter; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.CharArrayBuffer; /** * Default {@link org.apache.http.nio.NHttpMessageWriter} implementation * for {@link HttpResponse}s. * * @since 4.0 * * @deprecated (4.1) use {@link DefaultHttpResponseWriter} */ @SuppressWarnings("rawtypes") @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 HttpMessage message) throws IOException { final CharArrayBuffer buffer = lineFormatter.formatStatusLine (this.lineBuf, ((HttpResponse) message).getStatusLine()); this.sessionBuffer.writeLine(buffer); } } ././@LongLink0100644 0000000 0000000 00000000167 12613460517 011644 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/HttpRequestParser.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/codecs/Http0100644 0000000 0000000 00000005737 12613456024 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.impl.nio.codecs; 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.message.LineParser; import org.apache.http.message.ParserCursor; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; /** * Default {@link org.apache.http.nio.NHttpMessageParser} implementation * for {@link org.apache.http.HttpRequest}s. *

* 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.1) use {@link DefaultHttpRequestParser} */ @SuppressWarnings("rawtypes") @Deprecated public class HttpRequestParser extends AbstractMessageParser { private final HttpRequestFactory requestFactory; public HttpRequestParser( final SessionInputBuffer buffer, final LineParser parser, final HttpRequestFactory requestFactory, final HttpParams params) { super(buffer, parser, params); Args.notNull(requestFactory, "Request factory"); this.requestFactory = requestFactory; } @Override protected HttpMessage createMessage(final CharArrayBuffer buffer) throws HttpException, ParseException { final ParserCursor cursor = new ParserCursor(0, buffer.length()); final RequestLine requestLine = lineParser.parseRequestLine(buffer, cursor); return this.requestFactory.newHttpRequest(requestLine); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/ssl/0040755 0000000 0000000 00000000000 12613456024 030756 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000173 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/ssl/SSLClientIOEventDispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/ssl/SSLClie0100644 0000000 0000000 00000012667 12613456024 032150 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.ssl; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import org.apache.http.annotation.Immutable; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.impl.nio.reactor.SSLIOSession; import org.apache.http.impl.nio.reactor.SSLSetupHandler; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpClientIOTarget; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default implementation of {@link org.apache.http.nio.reactor.IOEventDispatch} * interface for SSL (encrypted) client-side HTTP connections. * * @since 4.1 * * @deprecated (4.2) use {@link org.apache.http.impl.nio.DefaultHttpClientIODispatch} */ @Deprecated @Immutable // provided injected dependencies are immutable public class SSLClientIOEventDispatch extends DefaultClientIOEventDispatch { private final SSLContext sslcontext; private final SSLSetupHandler sslHandler; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the client protocol handler. * @param sslcontext the SSL context. * @param sslHandler the SSL setup handler. * @param params HTTP parameters. */ public SSLClientIOEventDispatch( final NHttpClientHandler handler, final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { super(handler, params); Args.notNull(sslcontext, "SSL context"); Args.notNull(params, "HTTP parameters"); this.sslcontext = sslcontext; this.sslHandler = sslHandler; } /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the client protocol handler. * @param sslcontext the SSL context. * @param params HTTP parameters. */ public SSLClientIOEventDispatch( final NHttpClientHandler handler, final SSLContext sslcontext, final HttpParams params) { this(handler, sslcontext, null, params); } /** * Creates an instance of {@link SSLIOSession} decorating the given * {@link IOSession}. *

* This method can be overridden in a super class in order to provide * a different implementation of SSL I/O session. * * @param session the underlying I/O session. * @param sslcontext the SSL context. * @param sslHandler the SSL setup handler. * @return newly created SSL I/O session. */ protected SSLIOSession createSSLIOSession( final IOSession session, final SSLContext sslcontext, final SSLSetupHandler sslHandler) { return new SSLIOSession(session, sslcontext, sslHandler); } protected NHttpClientIOTarget createSSLConnection(final SSLIOSession ssliosession) { return super.createConnection(ssliosession); } @Override protected NHttpClientIOTarget createConnection(final IOSession session) { final SSLIOSession ssliosession = createSSLIOSession(session, this.sslcontext, this.sslHandler); session.setAttribute(SSLIOSession.SESSION_KEY, ssliosession); final NHttpClientIOTarget conn = createSSLConnection(ssliosession); try { ssliosession.initialize(); } catch (final SSLException ex) { this.handler.exception(conn, ex); ssliosession.shutdown(); } return conn; } @Override public void onConnected(final NHttpClientIOTarget conn) { final int timeout = HttpConnectionParams.getSoTimeout(this.params); conn.setSocketTimeout(timeout); final Object attachment = conn.getContext().getAttribute(IOSession.ATTACHMENT_KEY); this.handler.connected(conn, attachment); } } ././@LongLink0100644 0000000 0000000 00000000173 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/ssl/SSLServerIOEventDispatch.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/ssl/SSLServ0100644 0000000 0000000 00000012521 12613456024 032200 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.ssl; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import org.apache.http.annotation.Immutable; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.SSLIOSession; import org.apache.http.impl.nio.reactor.SSLSetupHandler; import org.apache.http.nio.NHttpServerIOTarget; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.Args; /** * Default implementation of {@link org.apache.http.nio.reactor.IOEventDispatch} * interface for SSL (encrypted) server-side HTTP connections. * * @since 4.1 * * @deprecated (4.2) use {@link org.apache.http.impl.nio.DefaultHttpServerIODispatch} */ @Deprecated @Immutable // provided injected dependencies are immutable public class SSLServerIOEventDispatch extends DefaultServerIOEventDispatch { private final SSLContext sslcontext; private final SSLSetupHandler sslHandler; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the server protocol handler. * @param sslcontext the SSL context. * @param sslHandler the SSL setup handler. * @param params HTTP parameters. */ public SSLServerIOEventDispatch( final NHttpServiceHandler handler, final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { super(handler, params); Args.notNull(sslcontext, "SSL context"); Args.notNull(params, "HTTP parameters"); this.sslcontext = sslcontext; this.sslHandler = sslHandler; } /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the server protocol handler. * @param sslcontext the SSL context. * @param params HTTP parameters. */ public SSLServerIOEventDispatch( final NHttpServiceHandler handler, final SSLContext sslcontext, final HttpParams params) { this(handler, sslcontext, null, params); } /** * Creates an instance of {@link SSLIOSession} decorating the given * {@link IOSession}. *

* This method can be overridden in a super class in order to provide * a different implementation of SSL I/O session. * * @param session the underlying I/O session. * @param sslcontext the SSL context. * @param sslHandler the SSL setup handler. * @return newly created SSL I/O session. */ protected SSLIOSession createSSLIOSession( final IOSession session, final SSLContext sslcontext, final SSLSetupHandler sslHandler) { return new SSLIOSession(session, sslcontext, sslHandler); } protected NHttpServerIOTarget createSSLConnection(final SSLIOSession ssliosession) { return super.createConnection(ssliosession); } @Override protected NHttpServerIOTarget createConnection(final IOSession session) { final SSLIOSession ssliosession = createSSLIOSession(session, this.sslcontext, this.sslHandler); session.setAttribute(SSLIOSession.SESSION_KEY, ssliosession); final NHttpServerIOTarget conn = createSSLConnection(ssliosession); try { ssliosession.initialize(); } catch (final SSLException ex) { this.handler.exception(conn, ex); ssliosession.shutdown(); } return conn; } @Override public void onConnected(final NHttpServerIOTarget conn) { final int timeout = HttpConnectionParams.getSoTimeout(this.params); conn.setSocketTimeout(timeout); this.handler.connected(conn); } } httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/0040755 0000000 0000000 00000000000 12613456024 031614 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000172 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSLIOSessionHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSL0100644 0000000 0000000 00000005254 12613456024 032203 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import java.net.SocketAddress; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import org.apache.http.params.HttpParams; /** * Callback interface that can be used to customize various aspects of * the TLS/SSl protocol. * * @since 4.0 * * @deprecated (4.2) Use {@link SSLSetupHandler} */ @Deprecated public interface SSLIOSessionHandler { /** * Triggered when the SSL connection is being initialized. Custom handlers * can use this callback to customize properties of the {@link SSLEngine} * used to establish the SSL session. * * @param sslengine the SSL engine. * @param params HTTP parameters. * @throws SSLException if case of SSL protocol error. */ void initalize(SSLEngine sslengine, HttpParams params) throws SSLException; /** * Triggered when the SSL connection has been established and initial SSL * handshake has been successfully completed. Custom handlers can use * this callback to verify properties of the {@link SSLSession}. * For instance this would be the right place to enforce SSL cipher * strength, validate certificate chain and do hostname checks. * * @param remoteAddress the remote address of the connection. * @param session newly created SSL session. * @throws SSLException if case of SSL protocol error. */ void verify(SocketAddress remoteAddress, SSLSession session) throws SSLException; } ././@LongLink0100644 0000000 0000000 00000000175 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSLSetupHandlerAdaptor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSL0100644 0000000 0000000 00000004266 12613456024 032205 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; /** * @deprecated (4.2) */ @Deprecated class SSLSetupHandlerAdaptor implements org.apache.http.nio.reactor.ssl.SSLSetupHandler { private final SSLSetupHandler handler; private HttpParams params; public SSLSetupHandlerAdaptor(final SSLSetupHandler handler) { super(); this.handler = handler; } public void initalize(final SSLEngine sslengine) throws SSLException { this.handler.initalize(sslengine, this.params != null ? this.params : new BasicHttpParams()); } public void verify(final IOSession iosession, final SSLSession sslsession) throws SSLException { this.handler.verify(iosession, sslsession); } public void setParams(final HttpParams params) { this.params = params; } } ././@LongLink0100644 0000000 0000000 00000000164 12613460517 011641 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SessionHandle.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/Ses0100644 0000000 0000000 00000005415 12613456024 032273 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import org.apache.http.nio.reactor.IOSession; import org.apache.http.util.Args; /** * Session handle class used by I/O reactor implementations to keep a reference * to a {@link IOSession} along with information about time of last I/O * operations on that session. * * @since 4.0 * * @deprecated (4.2) use {@link IOSessionImpl} */ @Deprecated public class SessionHandle { private final IOSession session; private final long startedTime; private long lastReadTime; private long lastWriteTime; private long lastAccessTime; public SessionHandle(final IOSession session) { super(); Args.notNull(session, "Session"); this.session = session; final long now = System.currentTimeMillis(); this.startedTime = now; this.lastReadTime = now; this.lastWriteTime = now; this.lastAccessTime = now; } public IOSession getSession() { return this.session; } public long getStartedTime() { return this.startedTime; } public long getLastReadTime() { return this.lastReadTime; } public long getLastWriteTime() { return this.lastWriteTime; } public long getLastAccessTime() { return this.lastAccessTime; } public void resetLastRead() { final long now = System.currentTimeMillis(); this.lastReadTime = now; this.lastAccessTime = now; } public void resetLastWrite() { final long now = System.currentTimeMillis(); this.lastWriteTime = now; this.lastAccessTime = now; } } ././@LongLink0100644 0000000 0000000 00000000166 12613460517 011643 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSLSetupHandler.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSL0100644 0000000 0000000 00000005333 12613456024 032201 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.HttpParams; /** * Callback interface that can be used to customize various aspects of * the TLS/SSl protocol. * * @since 4.1 * * @deprecated (4.2) use {@link org.apache.http.nio.reactor.ssl.SSLSetupHandler} */ @Deprecated public interface SSLSetupHandler { /** * Triggered when the SSL connection is being initialized. Custom handlers * can use this callback to customize properties of the {@link SSLEngine} * used to establish the SSL session. * * @param sslengine the SSL engine. * @param params HTTP parameters. * @throws SSLException if case of SSL protocol error. */ void initalize(SSLEngine sslengine, HttpParams params) throws SSLException; /** * Triggered when the SSL connection has been established and initial SSL * handshake has been successfully completed. Custom handlers can use * this callback to verify properties of the {@link SSLSession}. * For instance this would be the right place to enforce SSL cipher * strength, validate certificate chain and do hostname checks. * * @param iosession the underlying IOSession for the SSL connection. * @param sslsession newly created SSL session. * @throws SSLException if case of SSL protocol error. */ void verify(IOSession iosession, SSLSession sslsession) throws SSLException; } ././@LongLink0100644 0000000 0000000 00000000163 12613460517 011640 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSLIOSession.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSL0100644 0000000 0000000 00000006304 12613456024 032200 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.HttpParams; /** * A decorator class intended to transparently extend an {@link IOSession} * with transport layer security capabilities based on the SSL/TLS protocol. * * @since 4.0 * * @deprecated (4.2) use {@link org.apache.http.nio.reactor.ssl.SSLIOSession} */ @Deprecated public class SSLIOSession extends org.apache.http.nio.reactor.ssl.SSLIOSession { /** * @since 4.1 */ public SSLIOSession( final IOSession session, final SSLContext sslContext, final SSLSetupHandler handler) { super(session, org.apache.http.nio.reactor.ssl.SSLMode.CLIENT, sslContext, handler != null ? new SSLSetupHandlerAdaptor(handler) : null); } public SSLIOSession( final IOSession session, final SSLContext sslContext, final SSLIOSessionHandler handler) { super(session, org.apache.http.nio.reactor.ssl.SSLMode.CLIENT, sslContext, handler != null ? new SSLIOSessionHandlerAdaptor(handler) : null); } public synchronized void bind( final SSLMode mode, final HttpParams params) throws SSLException { final org.apache.http.nio.reactor.ssl.SSLSetupHandler handler = getSSLSetupHandler(); if (handler instanceof SSLIOSessionHandlerAdaptor) { ((SSLIOSessionHandlerAdaptor) handler).setParams(params); } else if (handler instanceof SSLSetupHandlerAdaptor) { ((SSLSetupHandlerAdaptor) handler).setParams(params); } initialize(convert(mode)); } private org.apache.http.nio.reactor.ssl.SSLMode convert(final SSLMode mode) { switch(mode) { case CLIENT: return org.apache.http.nio.reactor.ssl.SSLMode.CLIENT; case SERVER: return org.apache.http.nio.reactor.ssl.SSLMode.SERVER; } return null; } } ././@LongLink0100644 0000000 0000000 00000000201 12613460517 011631 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSLIOSessionHandlerAdaptor.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSL0100644 0000000 0000000 00000004333 12613456024 032200 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; /** * @deprecated (4.2) */ @Deprecated class SSLIOSessionHandlerAdaptor implements org.apache.http.nio.reactor.ssl.SSLSetupHandler { private final SSLIOSessionHandler handler; private HttpParams params; public SSLIOSessionHandlerAdaptor(final SSLIOSessionHandler handler) { super(); this.handler = handler; } public void initalize(final SSLEngine sslengine) throws SSLException { this.handler.initalize(sslengine, this.params != null ? this.params : new BasicHttpParams()); } public void verify(final IOSession iosession, final SSLSession sslsession) throws SSLException { this.handler.verify(iosession.getRemoteAddress(), sslsession); } public void setParams(final HttpParams params) { this.params = params; } } ././@LongLink0100644 0000000 0000000 00000000156 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSLMode.javahttpcomponents-core-4.4.4/httpcore-nio/src/main/java-deprecated/org/apache/http/impl/nio/reactor/SSL0100644 0000000 0000000 00000002467 12613456024 032206 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made 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.nio.reactor; /** * @since 4.0 * * @deprecated (4.2) */ @Deprecated public enum SSLMode { CLIENT, SERVER } httpcomponents-core-4.4.4/httpcore-ab/0040755 0000000 0000000 00000000000 12613456426 016511 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/pom.xml0100644 0000000 0000000 00000005540 12613456023 020020 0ustar000000000 0000000 4.0.0 org.apache.httpcomponents httpcomponents-core 4.4.4 httpcore-ab Apache HttpCore Benchmarking Tool Apache AB clone based on HttpCore http://hc.apache.org/httpcomponents-core-ga jar org.apache.httpcomponents httpcore ${project.version} compile commons-cli commons-cli 1.2 compile junit junit test maven-project-info-reports-plugin ${hc.project-info.version} false dependencies dependency-info summary httpcomponents-core-4.4.4/httpcore-ab/src/0040755 0000000 0000000 00000000000 12613456022 017270 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/test/0040755 0000000 0000000 00000000000 12613456022 020247 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/test/java/0040755 0000000 0000000 00000000000 12613456022 021170 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/test/java/org/0040755 0000000 0000000 00000000000 12613456022 021757 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/test/java/org/apache/0040755 0000000 0000000 00000000000 12613456022 023200 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/test/java/org/apache/http/0040755 0000000 0000000 00000000000 12613456022 024157 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/test/java/org/apache/http/benchmark/0040755 0000000 0000000 00000000000 12613456022 026111 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/test/java/org/apache/http/benchmark/SmokeTest.java0100644 0000000 0000000 00000006550 12613456022 030675 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import java.io.IOException; import java.net.URL; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class SmokeTest { private HttpServer server; @Before public void setup() throws Exception { server = new HttpServer(); server.registerHandler("/", new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new StringEntity("0123456789ABCDEF", ContentType.TEXT_PLAIN)); } }); server.start(); } @After public void shutdown() throws Exception { server.shutdown(); } @Test public void testBasics() throws Exception { final Config config = new Config(); config.setKeepAlive(true); config.setMethod("GET"); config.setUrl(new URL("http://localhost:" + server.getPort() + "/")); config.setThreads(3); config.setRequests(100); final HttpBenchmark httpBenchmark = new HttpBenchmark(config); final Results results = httpBenchmark.doExecute(); Assert.assertNotNull(results); Assert.assertEquals(16, results.getContentLength()); Assert.assertEquals(3, results.getConcurrencyLevel()); Assert.assertEquals(300, results.getKeepAliveCount()); Assert.assertEquals(300, results.getSuccessCount()); Assert.assertEquals(0, results.getFailureCount()); Assert.assertEquals(0, results.getWriteErrors()); Assert.assertEquals(300 * 16, results.getTotalBytes()); Assert.assertEquals(300 * 16, results.getTotalBytesRcvd()); } } httpcomponents-core-4.4.4/httpcore-ab/src/test/java/org/apache/http/benchmark/HttpServer.java0100644 0000000 0000000 00000014567 12613456022 031074 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; 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.HttpException; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpServerConnection; import org.apache.http.impl.DefaultBHttpServerConnection; 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.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 UriHttpRequestHandlerMapper reqistry; private final ServerSocket serversocket; private Thread listener; private volatile boolean shutdown; public HttpServer() throws IOException { super(); this.httpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer("TEST-SERVER/1.1"), new ResponseContent(), new ResponseConnControl() }); this.reqistry = new UriHttpRequestHandlerMapper(); this.serversocket = new ServerSocket(0); } public void registerHandler( final String pattern, final HttpRequestHandler handler) { this.reqistry.register(pattern, handler); } private HttpServerConnection acceptConnection() throws IOException { final Socket socket = this.serversocket.accept(); final DefaultBHttpServerConnection conn = new DefaultBHttpServerConnection(8 * 1024); conn.bind(socket); 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() { @Override 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, DefaultConnectionReuseStrategy.INSTANCE, DefaultHttpResponseFactory.INSTANCE, reqistry, null); // 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) {} } } } } httpcomponents-core-4.4.4/httpcore-ab/src/main/0040755 0000000 0000000 00000000000 12613456022 020214 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/main/java/0040755 0000000 0000000 00000000000 12613456022 021135 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/0040755 0000000 0000000 00000000000 12613456022 021724 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/0040755 0000000 0000000 00000000000 12613456022 023145 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/0040755 0000000 0000000 00000000000 12613456022 024124 5ustar000000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/0040755 0000000 0000000 00000000000 12613456023 026057 5ustar000000000 0000000 ././@LongLink0100644 0000000 0000000 00000000150 12613460517 011634 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/CountingOutputStream.javahttpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/CountingOutputStream.j0100644 0000000 0000000 00000003757 12613456023 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.benchmark; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; class CountingOutputStream extends FilterOutputStream { private final Stats stats; CountingOutputStream(final OutputStream outstream, final Stats stats) { super(outstream); this.stats = stats; } @Override public void write(final int b) throws IOException { this.out.write(b); this.stats.incTotalBytesSent(1); } @Override public void write(final byte[] b) throws IOException { this.out.write(b); this.stats.incTotalBytesSent(b.length); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { this.out.write(b, off, len); this.stats.incTotalBytesSent(len); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkConnection.javahttpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkConnection.ja0100644 0000000 0000000 00000004040 12613456023 032300 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.impl.DefaultBHttpClientConnection; import org.apache.http.io.SessionInputBuffer; import org.apache.http.io.SessionOutputBuffer; class BenchmarkConnection extends DefaultBHttpClientConnection { private final Stats stats; BenchmarkConnection(final int bufsize, final Stats stats) { super(bufsize); this.stats = stats; } @Override protected OutputStream createOutputStream(final long len, final SessionOutputBuffer outbuffer) { return new CountingOutputStream(super.createOutputStream(len, outbuffer), this.stats); } @Override protected InputStream createInputStream(final long len, final SessionInputBuffer inbuffer) { return new CountingInputStream(super.createInputStream(len, inbuffer), this.stats); } } httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/DefaultHeader.java0100644 0000000 0000000 00000002714 12613456023 031420 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import org.apache.http.message.BasicHeader; class DefaultHeader extends BasicHeader { private static final long serialVersionUID = 3465786867105185103L; public DefaultHeader(final String name, final String value) { super(name, value); } } httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/ResultProcessor.java0100644 0000000 0000000 00000013352 12613456023 032101 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import java.text.NumberFormat; import org.apache.http.HttpHost; public class ResultProcessor { static NumberFormat nf2 = NumberFormat.getInstance(); static NumberFormat nf3 = NumberFormat.getInstance(); static NumberFormat nf6 = NumberFormat.getInstance(); static { nf2.setMaximumFractionDigits(2); nf2.setMinimumFractionDigits(2); nf3.setMaximumFractionDigits(3); nf3.setMinimumFractionDigits(3); nf6.setMaximumFractionDigits(6); nf6.setMinimumFractionDigits(6); } static Results collectResults(final BenchmarkWorker[] workers, final HttpHost host, final String uri) { long totalTimeNano = 0; long successCount = 0; long failureCount = 0; long writeErrors = 0; long keepAliveCount = 0; long totalBytesRcvd = 0; long totalBytesSent = 0; final Stats stats = workers[0].getStats(); for (final BenchmarkWorker worker : workers) { final Stats s = worker.getStats(); totalTimeNano += s.getDuration(); successCount += s.getSuccessCount(); failureCount += s.getFailureCount(); writeErrors += s.getWriteErrors(); keepAliveCount += s.getKeepAliveCount(); totalBytesRcvd += s.getTotalBytesRecv(); totalBytesSent += s.getTotalBytesSent(); } final Results results = new Results(); results.serverName = stats.getServerName(); results.hostName = host.getHostName(); results.hostPort = host.getPort() > 0 ? host.getPort() : host.getSchemeName().equalsIgnoreCase("https") ? 443 : 80; results.documentPath = uri; results.contentLength = stats.getContentLength(); results.concurrencyLevel = workers.length; results.totalTimeNano = totalTimeNano; results.successCount = successCount; results.failureCount = failureCount; results.writeErrors = writeErrors; results.keepAliveCount = keepAliveCount; results.totalBytesRcvd = totalBytesRcvd; results.totalBytesSent = totalBytesSent; results.totalBytes = totalBytesRcvd + (totalBytesSent > 0 ? totalBytesSent : 0); return results; } static void printResults(final Results results) { final int threads = results.getConcurrencyLevel(); final double totalTimeMs = (results.getTotalTimeNano() / threads) / 1000000; // convert nano secs to milli secs final double timePerReqMs = totalTimeMs / results.getSuccessCount(); final double totalTimeSec = totalTimeMs / 1000; final double reqsPerSec = results.getSuccessCount() / totalTimeSec; System.out.println("\nServer Software:\t\t" + results.getServerName()); System.out.println( "Server Hostname:\t\t" + results.getHostName()); System.out.println( "Server Port:\t\t\t" + Integer.valueOf(results.getHostPort())); System.out.println( "Document Path:\t\t\t" + results.getDocumentPath()); System.out.println( "Document Length:\t\t" + results.getContentLength() + " bytes\n"); System.out.println( "Concurrency Level:\t\t" + results.getConcurrencyLevel()); System.out.println( "Time taken for tests:\t\t" + nf6.format(totalTimeSec) + " seconds"); System.out.println( "Complete requests:\t\t" + results.getSuccessCount()); System.out.println( "Failed requests:\t\t" + results.getFailureCount()); System.out.println( "Write errors:\t\t\t" + results.getWriteErrors()); System.out.println( "Kept alive:\t\t\t" + results.getKeepAliveCount()); System.out.println( "Total transferred:\t\t" + results.getTotalBytes() + " bytes"); System.out.println( "Requests per second:\t\t" + nf2.format(reqsPerSec) + " [#/sec] (mean)"); System.out.println( "Time per request:\t\t" + nf3.format(timePerReqMs * results.getConcurrencyLevel()) + " [ms] (mean)"); System.out.println( "Time per request:\t\t" + nf3.format(timePerReqMs) + " [ms] (mean, across all concurrent requests)"); System.out.println( "Transfer rate:\t\t\t" + nf2.format(results.getTotalBytesRcvd() / 1000 / totalTimeSec) + " [Kbytes/sec] received"); System.out.println( "\t\t\t\t" + (results.getTotalBytesSent() > 0 ? nf2.format(results.getTotalBytesSent() / 1000 / totalTimeSec) : Integer.valueOf(-1)) + " kb/s sent"); System.out.println( "\t\t\t\t" + nf2.format(results.getTotalBytes() / 1000 / totalTimeSec) + " kb/s total"); } } httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/package-info.java0100644 0000000 0000000 00000002372 12613456023 031247 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ /** * Apache Bench (AB) clone based on HttpCore. */ package org.apache.http.benchmark; httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/CommandLineUtils.java0100644 0000000 0000000 00000020222 12613456023 032124 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; public class CommandLineUtils { public static Options getOptions() { final Option iopt = new Option("i", false, "Do HEAD requests instead of GET (deprecated)"); iopt.setRequired(false); final Option oopt = new Option("o", false, "Use HTTP/S 1.0 instead of 1.1 (default)"); oopt.setRequired(false); final Option kopt = new Option("k", false, "Enable the HTTP KeepAlive feature, " + "i.e., perform multiple requests within one HTTP session. " + "Default is no KeepAlive"); kopt.setRequired(false); final Option uopt = new Option("u", false, "Chunk entity. Default is false"); uopt.setRequired(false); final Option xopt = new Option("x", false, "Use Expect-Continue. Default is false"); xopt.setRequired(false); final Option gopt = new Option("g", false, "Accept GZip. Default is false"); gopt.setRequired(false); final Option nopt = new Option("n", true, "Number of requests to perform for the " + "benchmarking session. The default is to just perform a single " + "request which usually leads to non-representative benchmarking " + "results"); nopt.setRequired(false); nopt.setArgName("requests"); final Option copt = new Option("c", true, "Concurrency while performing the " + "benchmarking session. The default is to just use a single thread/client"); copt.setRequired(false); copt.setArgName("concurrency"); final Option popt = new Option("p", true, "File containing data to POST or PUT"); popt.setRequired(false); popt.setArgName("Payload file"); final Option mopt = new Option("m", true, "HTTP Method. Default is POST. " + "Possible options are GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE"); mopt.setRequired(false); mopt.setArgName("HTTP method"); final Option Topt = new Option("T", true, "Content-type header to use for POST/PUT data"); Topt.setRequired(false); Topt.setArgName("content-type"); final Option topt = new Option("t", true, "Client side socket timeout (in ms) - default 60 Secs"); topt.setRequired(false); topt.setArgName("socket-Timeout"); final Option Hopt = new Option("H", true, "Add arbitrary header line, " + "eg. 'Accept-Encoding: gzip' inserted after all normal " + "header lines. (repeatable as -H \"h1: v1\",\"h2: v2\" etc)"); Hopt.setRequired(false); Hopt.setArgName("header"); final Option vopt = new Option("v", true, "Set verbosity level - 4 and above " + "prints response content, 3 and above prints " + "information on headers, 2 and above prints response codes (404, 200, " + "etc.), 1 and above prints warnings and info"); vopt.setRequired(false); vopt.setArgName("verbosity"); final Option hopt = new Option("h", false, "Display usage information"); nopt.setRequired(false); final Options options = new Options(); options.addOption(iopt); options.addOption(mopt); options.addOption(uopt); options.addOption(xopt); options.addOption(gopt); options.addOption(kopt); options.addOption(nopt); options.addOption(copt); options.addOption(popt); options.addOption(Topt); options.addOption(vopt); options.addOption(Hopt); options.addOption(hopt); options.addOption(topt); options.addOption(oopt); return options; } public static void parseCommandLine(final CommandLine cmd, final Config config) { if (cmd.hasOption('v')) { final String s = cmd.getOptionValue('v'); try { config.setVerbosity(Integer.parseInt(s)); } catch (final NumberFormatException ex) { printError("Invalid verbosity level: " + s); } } if (cmd.hasOption('k')) { config.setKeepAlive(true); } if (cmd.hasOption('c')) { final String s = cmd.getOptionValue('c'); try { config.setThreads(Integer.parseInt(s)); } catch (final NumberFormatException ex) { printError("Invalid number for concurrency: " + s); } } if (cmd.hasOption('n')) { final String s = cmd.getOptionValue('n'); try { config.setRequests(Integer.parseInt(s)); } catch (final NumberFormatException ex) { printError("Invalid number of requests: " + s); } } if (cmd.hasOption('p')) { final File file = new File(cmd.getOptionValue('p')); if (!file.exists()) { printError("File not found: " + file); } config.setPayloadFile(file); } if (cmd.hasOption('T')) { config.setContentType(cmd.getOptionValue('T')); } if (cmd.hasOption('i')) { config.setHeadInsteadOfGet(true); } if (cmd.hasOption('H')) { final String headerStr = cmd.getOptionValue('H'); config.setHeaders(headerStr.split(",")); } if (cmd.hasOption('t')) { final String t = cmd.getOptionValue('t'); try { config.setSocketTimeout(Integer.parseInt(t)); } catch (final NumberFormatException ex) { printError("Invalid socket timeout: " + t); } } if (cmd.hasOption('o')) { config.setUseHttp1_0(true); } if (cmd.hasOption('m')) { config.setMethod(cmd.getOptionValue('m')); } else if (cmd.hasOption('p')) { config.setMethod("POST"); } if (cmd.hasOption('u')) { config.setUseChunking(true); } if (cmd.hasOption('x')) { config.setUseExpectContinue(true); } if (cmd.hasOption('g')) { config.setUseAcceptGZip(true); } final String[] cmdargs = cmd.getArgs(); if (cmdargs.length > 0) { try { config.setUrl(new URL(cmdargs[0])); } catch (final MalformedURLException e) { printError("Invalid request URL : " + cmdargs[0]); } } } static void showUsage(final Options options) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("HttpBenchmark [options] [http://]hostname[:port]/path?query", options); } static void printError(final String msg) { System.err.println(msg); showUsage(getOptions()); System.exit(-1); } } httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/Stats.java0100644 0000000 0000000 00000007347 12613456023 030030 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; /** * Helper to gather statistics for an {@link HttpBenchmark HttpBenchmark}. * * * @since 4.0 */ public class Stats { private long startTime = -1; // nano seconds - does not represent an actual time private long finishTime = -1; // nano seconds - does not represent an actual time private int successCount = 0; private int failureCount = 0; private int writeErrors = 0; private int keepAliveCount = 0; private String serverName = null; private long totalBytesRecv = 0; private long totalBytesSent = 0; private long contentLength = -1; public Stats() { super(); } public void start() { this.startTime = System.nanoTime(); } public void finish() { this.finishTime = System.nanoTime(); } public long getFinishTime() { return this.finishTime; } public long getStartTime() { return this.startTime; } /** * Total execution time measured in nano seconds * * @return duration in nanoseconds */ public long getDuration() { // we are using System.nanoTime() and the return values could be negative // but its only the difference that we are concerned about return this.finishTime - this.startTime; } public void incSuccessCount() { this.successCount++; } public int getSuccessCount() { return this.successCount; } public void incFailureCount() { this.failureCount++; } public int getFailureCount() { return this.failureCount; } public void incWriteErrors() { this.writeErrors++; } public int getWriteErrors() { return this.writeErrors; } public void incKeepAliveCount() { this.keepAliveCount++; } public int getKeepAliveCount() { return this.keepAliveCount; } public long getTotalBytesRecv() { return this.totalBytesRecv; } public void incTotalBytesRecv(final long n) { this.totalBytesRecv += n; } public long getTotalBytesSent() { return this.totalBytesSent; } public void incTotalBytesSent(final long n) { this.totalBytesSent += n; } public long getContentLength() { return this.contentLength; } public void setContentLength(final long contentLength) { this.contentLength = contentLength; } public String getServerName() { return this.serverName; } public void setServerName(final String serverName) { this.serverName = serverName; } } httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkWorker.java0100644 0000000 0000000 00000022774 12613456023 032017 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.Charset; import javax.net.SocketFactory; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.protocol.HTTP; 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; /** * Worker thread for the {@link HttpBenchmark HttpBenchmark}. * * * @since 4.0 */ class BenchmarkWorker implements Runnable { private final byte[] buffer = new byte[4096]; private final HttpCoreContext context; private final HttpProcessor httpProcessor; private final HttpRequestExecutor httpexecutor; private final ConnectionReuseStrategy connstrategy; private final HttpRequest request; private final HttpHost targetHost; private final Config config; private final SocketFactory socketFactory; private final Stats stats = new Stats(); public BenchmarkWorker( final HttpRequest request, final HttpHost targetHost, final SocketFactory socketFactory, final Config config) { super(); this.context = new HttpCoreContext(); this.request = request; this.targetHost = targetHost; this.config = config; this.httpProcessor = new ImmutableHttpProcessor( new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent("HttpCore-AB/1.1"), new RequestExpectContinue(this.config.isUseExpectContinue())); this.httpexecutor = new HttpRequestExecutor(); this.connstrategy = DefaultConnectionReuseStrategy.INSTANCE; this.socketFactory = socketFactory; } @Override public void run() { HttpResponse response = null; final BenchmarkConnection conn = new BenchmarkConnection(8 * 1024, stats); final String scheme = targetHost.getSchemeName(); final String hostname = targetHost.getHostName(); int port = targetHost.getPort(); if (port == -1) { if (scheme.equalsIgnoreCase("https")) { port = 443; } else { port = 80; } } // Populate the execution context this.context.setTargetHost(this.targetHost); stats.start(); final int count = config.getRequests(); for (int i = 0; i < count; i++) { try { resetHeader(request); if (!conn.isOpen()) { final Socket socket; if (socketFactory != null) { socket = socketFactory.createSocket(); } else { socket = new Socket(); } final int timeout = config.getSocketTimeout(); socket.setSoTimeout(timeout); socket.connect(new InetSocketAddress(hostname, port), timeout); conn.bind(socket); } try { // Prepare request this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context); // Execute request and get a response response = this.httpexecutor.execute(this.request, conn, this.context); // Finalize response this.httpexecutor.postProcess(response, this.httpProcessor, this.context); } catch (final HttpException e) { stats.incWriteErrors(); if (config.getVerbosity() >= 2) { System.err.println("Failed HTTP request : " + e.getMessage()); } conn.shutdown(); continue; } verboseOutput(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { stats.incSuccessCount(); } else { stats.incFailureCount(); } final HttpEntity entity = response.getEntity(); if (entity != null) { final ContentType ct = ContentType.getOrDefault(entity); Charset charset = ct.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } long contentlen = 0; final InputStream instream = entity.getContent(); int l; while ((l = instream.read(this.buffer)) != -1) { contentlen += l; if (config.getVerbosity() >= 4) { final String s = new String(this.buffer, 0, l, charset); System.out.print(s); } } instream.close(); stats.setContentLength(contentlen); } if (config.getVerbosity() >= 4) { System.out.println(); System.out.println(); } if (!config.isKeepAlive() || !this.connstrategy.keepAlive(response, this.context)) { conn.close(); } else { stats.incKeepAliveCount(); } } catch (final IOException ex) { stats.incFailureCount(); if (config.getVerbosity() >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } catch (final Exception ex) { stats.incFailureCount(); if (config.getVerbosity() >= 2) { System.err.println("Generic error: " + ex.getMessage()); } } } stats.finish(); if (response != null) { final Header header = response.getFirstHeader("Server"); if (header != null) { stats.setServerName(header.getValue()); } } try { conn.close(); } catch (final IOException ex) { stats.incFailureCount(); if (config.getVerbosity() >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } } private void verboseOutput(final HttpResponse response) { if (config.getVerbosity() >= 3) { System.out.println(">> " + request.getRequestLine().toString()); final Header[] headers = request.getAllHeaders(); for (final Header header : headers) { System.out.println(">> " + header.toString()); } System.out.println(); } if (config.getVerbosity() >= 2) { System.out.println(response.getStatusLine().getStatusCode()); } if (config.getVerbosity() >= 3) { System.out.println("<< " + response.getStatusLine().toString()); final Header[] headers = response.getAllHeaders(); for (final Header header : headers) { System.out.println("<< " + header.toString()); } System.out.println(); } } private static void resetHeader(final HttpRequest request) { for (final HeaderIterator it = request.headerIterator(); it.hasNext();) { final Header header = it.nextHeader(); if (!(header instanceof DefaultHeader)) { it.remove(); } } } public Stats getStats() { return stats; } } httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/HttpBenchmark.java0100644 0000000 0000000 00000021464 12613456023 031460 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import java.io.File; import java.net.URL; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpVersion; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.protocol.HTTP; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; /** * Main program of the HTTP benchmark. * * * @since 4.0 */ public class HttpBenchmark { private final Config config; public static void main(final String[] args) throws Exception { final Options options = CommandLineUtils.getOptions(); final CommandLineParser parser = new PosixParser(); final CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption('h') || cmd.getArgs().length != 1) { CommandLineUtils.showUsage(options); System.exit(1); } final Config config = new Config(); CommandLineUtils.parseCommandLine(cmd, config); if (config.getUrl() == null) { CommandLineUtils.showUsage(options); System.exit(1); } final HttpBenchmark httpBenchmark = new HttpBenchmark(config); httpBenchmark.execute(); } public HttpBenchmark(final Config config) { super(); this.config = config != null ? config : new Config(); } private HttpRequest createRequest() { final URL url = config.getUrl(); HttpEntity entity = null; // Prepare requests for each thread if (config.getPayloadFile() != null) { final FileEntity fe = new FileEntity(config.getPayloadFile()); fe.setContentType(config.getContentType()); fe.setChunked(config.isUseChunking()); entity = fe; } else if (config.getPayloadText() != null) { final StringEntity se = new StringEntity(config.getPayloadText(), ContentType.parse(config.getContentType())); se.setChunked(config.isUseChunking()); entity = se; } final HttpVersion ver = config.isUseHttp1_0() ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1; final HttpRequest request; if ("POST".equals(config.getMethod())) { final BasicHttpEntityEnclosingRequest httppost = new BasicHttpEntityEnclosingRequest("POST", url.getPath(), ver); httppost.setEntity(entity); request = httppost; } else if ("PUT".equals(config.getMethod())) { final BasicHttpEntityEnclosingRequest httpput = new BasicHttpEntityEnclosingRequest("PUT", url.getPath(), ver); httpput.setEntity(entity); request = httpput; } else { String path = url.getPath(); if (url.getQuery() != null && url.getQuery().length() > 0) { path += "?" + url.getQuery(); } else if (path.trim().length() == 0) { path = "/"; } request = new BasicHttpRequest(config.getMethod(), path, ver); } if (!config.isKeepAlive()) { request.addHeader(new DefaultHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); } final String[] headers = config.getHeaders(); if (headers != null) { for (final String s : headers) { final int pos = s.indexOf(':'); if (pos != -1) { final Header header = new DefaultHeader(s.substring(0, pos).trim(), s.substring(pos + 1)); request.addHeader(header); } } } if (config.isUseAcceptGZip()) { request.addHeader(new DefaultHeader("Accept-Encoding", "gzip")); } if (config.getSoapAction() != null && config.getSoapAction().length() > 0) { request.addHeader(new DefaultHeader("SOAPAction", config.getSoapAction())); } return request; } public String execute() throws Exception { final Results results = doExecute(); ResultProcessor.printResults(results); return ""; } public Results doExecute() throws Exception { final URL url = config.getUrl(); final HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); final ThreadPoolExecutor workerPool = new ThreadPoolExecutor( config.getThreads(), config.getThreads(), 5, TimeUnit.SECONDS, new LinkedBlockingQueue(), new ThreadFactory() { @Override public Thread newThread(final Runnable r) { return new Thread(r, "ClientPool"); } }); workerPool.prestartAllCoreThreads(); SocketFactory socketFactory = null; if ("https".equals(host.getSchemeName())) { final SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.useProtocol("SSL"); if (config.isDisableSSLVerification()) { sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }); } else if (config.getTrustStorePath() != null) { sslContextBuilder.loadTrustMaterial( new File(config.getTrustStorePath()), config.getTrustStorePassword() != null ? config.getTrustStorePassword().toCharArray() : null); } if (config.getIdentityStorePath() != null) { sslContextBuilder.loadKeyMaterial( new File(config.getIdentityStorePath()), config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray() : null, config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray() : null); } final SSLContext sslContext = sslContextBuilder.build(); socketFactory = sslContext.getSocketFactory(); } final BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()]; for (int i = 0; i < workers.length; i++) { workers[i] = new BenchmarkWorker( createRequest(), host, socketFactory, config); workerPool.execute(workers[i]); } while (workerPool.getCompletedTaskCount() < config.getThreads()) { Thread.yield(); try { Thread.sleep(1000); } catch (final InterruptedException ignore) { } } workerPool.shutdown(); return ResultProcessor.collectResults(workers, host, config.getUrl().toString()); } } ././@LongLink0100644 0000000 0000000 00000000147 12613460517 011642 Lustar 0000000 0000000 httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/CountingInputStream.javahttpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/CountingInputStream.ja0100644 0000000 0000000 00000004704 12613456023 032357 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; class CountingInputStream extends FilterInputStream { private final Stats stats; CountingInputStream(final InputStream instream, final Stats stats) { super(instream); this.stats = stats; } @Override public int read() throws IOException { final int b = this.in.read(); if (b != -1) { this.stats.incTotalBytesRecv(1); } return b; } @Override public int read(final byte[] b) throws IOException { final int bytesRead = this.in.read(b); if (bytesRead > 0) { this.stats.incTotalBytesRecv(bytesRead); } return bytesRead; } @Override public int read(final byte[] b, final int off, final int len) throws IOException { final int bytesRead = this.in.read(b, off, len); if (bytesRead > 0) { this.stats.incTotalBytesRecv(bytesRead); } return bytesRead; } @Override public long skip(final long n) throws IOException { final long bytesRead = this.in.skip(n); if (bytesRead > 0) { this.stats.incTotalBytesRecv(bytesRead); } return bytesRead; } } httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/Results.java0100644 0000000 0000000 00000007277 12613456023 030375 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; /** * Benchmark results * * @since 4.3 */ public final class Results { String serverName; String hostName; int hostPort; String documentPath; long contentLength; int concurrencyLevel; long totalTimeNano; long successCount; long failureCount; long writeErrors; long keepAliveCount; long totalBytesRcvd; long totalBytesSent; long totalBytes; Results() { super(); this.contentLength = -1; } public String getServerName() { return serverName; } public String getHostName() { return hostName; } public int getHostPort() { return hostPort; } public String getDocumentPath() { return documentPath; } public long getContentLength() { return contentLength; } public int getConcurrencyLevel() { return concurrencyLevel; } public long getTotalTimeNano() { return totalTimeNano; } public long getSuccessCount() { return successCount; } public long getFailureCount() { return failureCount; } public long getWriteErrors() { return writeErrors; } public long getKeepAliveCount() { return keepAliveCount; } public long getTotalBytesRcvd() { return totalBytesRcvd; } public long getTotalBytesSent() { return totalBytesSent; } public long getTotalBytes() { return totalBytes; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("[serverName=").append(serverName) .append(", hostName=").append(hostName) .append(", hostPort=").append(hostPort) .append(", documentPath=").append(documentPath) .append(", contentLength=").append(contentLength) .append(", concurrencyLevel=").append(concurrencyLevel) .append(", totalTimeNano=").append(totalTimeNano) .append(", successCount=").append(successCount) .append(", failureCount=").append(failureCount) .append(", writeErrors=").append(writeErrors) .append(", keepAliveCount=").append(keepAliveCount) .append(", totalBytesRcvd=").append(totalBytesRcvd) .append(", totalBytesSent=").append(totalBytesSent) .append(", totalBytes=").append(totalBytes) .append("]"); return builder.toString(); } } httpcomponents-core-4.4.4/httpcore-ab/src/main/java/org/apache/http/benchmark/Config.java0100644 0000000 0000000 00000016777 12613456023 030146 0ustar000000000 0000000 /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.http.benchmark; import java.io.File; import java.net.URL; public class Config { private URL url; private int requests; private int threads; private boolean keepAlive; private int verbosity; private boolean headInsteadOfGet; private boolean useHttp1_0; private String contentType; private String[] headers; private int socketTimeout; private String method = "GET"; private boolean useChunking; private boolean useExpectContinue; private boolean useAcceptGZip; private File payloadFile = null; private String payloadText = null; private String soapAction = null; private boolean disableSSLVerification = true; private String trustStorePath = null; private String identityStorePath = null; private String trustStorePassword = null; private String identityStorePassword = null; public Config() { super(); this.url = null; this.requests = 1; this.threads = 1; this.keepAlive = false; this.verbosity = 0; this.headInsteadOfGet = false; this.useHttp1_0 = false; this.payloadFile = null; this.payloadText = null; this.contentType = null; this.headers = null; this.socketTimeout = 60000; } public URL getUrl() { return url; } public void setUrl(final URL url) { this.url = url; } public int getRequests() { return requests; } public void setRequests(final int requests) { this.requests = requests; } public int getThreads() { return threads; } public void setThreads(final int threads) { this.threads = threads; } public boolean isKeepAlive() { return keepAlive; } public void setKeepAlive(final boolean keepAlive) { this.keepAlive = keepAlive; } public int getVerbosity() { return verbosity; } public void setVerbosity(final int verbosity) { this.verbosity = verbosity; } public boolean isHeadInsteadOfGet() { return headInsteadOfGet; } public void setHeadInsteadOfGet(final boolean headInsteadOfGet) { this.headInsteadOfGet = headInsteadOfGet; this.method = "HEAD"; } public boolean isUseHttp1_0() { return useHttp1_0; } public void setUseHttp1_0(final boolean useHttp1_0) { this.useHttp1_0 = useHttp1_0; } public File getPayloadFile() { return payloadFile; } public void setPayloadFile(final File payloadFile) { this.payloadFile = payloadFile; } public String getContentType() { return contentType; } public void setContentType(final String contentType) { this.contentType = contentType; } public String[] getHeaders() { return headers; } public void setHeaders(final String[] headers) { this.headers = headers; } public int getSocketTimeout() { return socketTimeout; } public void setSocketTimeout(final int socketTimeout) { this.socketTimeout = socketTimeout; } public void setMethod(final String method) { this.method = method; } public void setUseChunking(final boolean useChunking) { this.useChunking = useChunking; } public void setUseExpectContinue(final boolean useExpectContinue) { this.useExpectContinue = useExpectContinue; } public void setUseAcceptGZip(final boolean useAcceptGZip) { this.useAcceptGZip = useAcceptGZip; } public String getMethod() { return method; } public boolean isUseChunking() { return useChunking; } public boolean isUseExpectContinue() { return useExpectContinue; } public boolean isUseAcceptGZip() { return useAcceptGZip; } public String getPayloadText() { return payloadText; } public String getSoapAction() { return soapAction; } public boolean isDisableSSLVerification() { return disableSSLVerification; } public String getTrustStorePath() { return trustStorePath; } public String getIdentityStorePath() { return identityStorePath; } public String getTrustStorePassword() { return trustStorePassword; } public String getIdentityStorePassword() { return identityStorePassword; } public void setPayloadText(final String payloadText) { this.payloadText = payloadText; } public void setSoapAction(final String soapAction) { this.soapAction = soapAction; } public void setDisableSSLVerification(final boolean disableSSLVerification) { this.disableSSLVerification = disableSSLVerification; } public void setTrustStorePath(final String trustStorePath) { this.trustStorePath = trustStorePath; } public void setIdentityStorePath(final String identityStorePath) { this.identityStorePath = identityStorePath; } public void setTrustStorePassword(final String trustStorePassword) { this.trustStorePassword = trustStorePassword; } public void setIdentityStorePassword(final String identityStorePassword) { this.identityStorePassword = identityStorePassword; } public Config copy() { final Config copy = new Config(); copy.url = this.url; copy.requests = this.requests; copy.threads = this.threads; copy.keepAlive = this.keepAlive; copy.verbosity = this.verbosity; copy.headInsteadOfGet = this.headInsteadOfGet; copy.useHttp1_0 = this.useHttp1_0; copy.contentType = this.contentType; copy.headers = this.headers; copy.socketTimeout = this.socketTimeout; copy.method = this.method; copy.useChunking = this.useChunking; copy.useExpectContinue = this.useExpectContinue; copy.useAcceptGZip = this.useAcceptGZip; copy.payloadFile = this.payloadFile; copy.payloadText = this.payloadText; copy.soapAction = this.soapAction; copy.disableSSLVerification = this.disableSSLVerification; copy.trustStorePath = this.trustStorePath; copy.identityStorePath = this.identityStorePath; copy.trustStorePassword = this.trustStorePassword; copy.identityStorePassword = this.identityStorePassword; return copy; } } httpcomponents-core-4.4.4/src/0040755 0000000 0000000 00000000000 12613456012 015057 5ustar000000000 0000000 httpcomponents-core-4.4.4/src/docbkx/0040755 0000000 0000000 00000000000 12613456013 016332 5ustar000000000 0000000 httpcomponents-core-4.4.4/src/docbkx/nio.xml0100644 0000000 0000000 00000321531 12613456012 017642 0ustar000000000 0000000 Asynchronous I/O based on NIO Asynchronous I/O model may be more appropriate for those scenarios where raw data throughput is less important than the ability to handle thousands of simultaneous connections in a scalable, resource efficient manner. Asynchronous I/O is arguably more complex and usually requires a special care when dealing with large message payloads.

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); ]]>
Pipelined request execution In addition to the normal request / response execution mode HttpAsyncRequester is also capable of executing requests in the so called pipelined mode whereby several requests are immediately written out to the underlying connection. Please note that entity enclosing requests can be executed in the pipelined mode but the 'expect: continue' handshake should be disabled (request messages should contains no 'Expect: 100-continue' header). HttpAsyncRequester requester = new HttpAsyncRequester(httpproc); HttpHost target = new HttpHost("www.apache.org"); List requestProducers = Arrays.asList( new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/index.html")), new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/foundation/index.html")), new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/foundation/how-it-works.html")) ); List responseConsumers = Arrays.asList( new BasicAsyncResponseConsumer(), new BasicAsyncResponseConsumer(), new BasicAsyncResponseConsumer() ); HttpCoreContext context = HttpCoreContext.create(); Future> future = requester.executePipelined( target, requestProducers, responseConsumers, pool, context, null); ]]> Please note that older web servers and especially older HTTP proxies may be unable to handle pipelined requests correctly. Use the pipelined execution mode with caution.
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 TLS and disable SSL sslengine.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }); // 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 TLS and disable SSL sslengine.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }); } 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.
Embedded non-blocking HTTP server As of version 4.4 HttpCore ships with an embedded non-blocking HTTP server based on non-blocking I/O components described above. requestHandler = <...> HttpProcessor httpProcessor = <...> SocketConfig socketConfig = SocketConfig.custom() .setSoTimeout(15000) .setTcpNoDelay(true) .build(); final HttpServer server = ServerBootstrap.bootstrap() .setListenerPort(8080) .setHttpProcessor(httpProcessor) .setSocketConfig(socketConfig) .setExceptionLogger(new StdErrorExceptionLogger()) .registerHandler("*", requestHandler) .create(); server.start(); server.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(5, TimeUnit.SECONDS); } }); ]]>
httpcomponents-core-4.4.4/src/docbkx/preface.xml0100644 0000000 0000000 00000006521 12613456012 020461 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.4.4/src/docbkx/blocking-io.xml0100644 0000000 0000000 00000064672 12613456013 021265 0ustar000000000 0000000 Blocking I/O model Blocking (or classic) I/O in Java represents a highly efficient and convenient I/O model well suited for high performance applications where the number of concurrent connections is relatively moderate. Modern JVMs are capable of efficient context switching and the blocking I/O model should offer the best performance in terms of raw data throughput as long as the number of concurrent connections is below one thousand and connections are mostly busy transmitting data. However for applications where connections stay idle most of the time the overhead of context switching may become substantial and a non-blocking I/O model may present a better alternative.
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.
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, true); } ]]> 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); ]]> Generally it is considered to be a responsibility of the consumer to keep track of connections leased from the pool and to ensure their immediate release as soon as they are no longer needed or actively used. Nevertheless BasicConnPool provides protected methods to enumerate available idle connections and those currently leased from the pool. This enables the pool consumer to query connection state and selectively terminate connections meeting a particular criterion. callback) { super.enumAvailable(callback); } @Override protected void enumLeased(final PoolEntryCallback callback) { super.enumLeased(callback); } } ]]> () { @Override public void process(final PoolEntry entry) { Date creationTime = new Date(entry.getCreated()); if (creationTime.before(someTime)) { entry.close(); } } }); ]]>
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.
Embedded HTTP server As of version 4.4 HttpCore ships with an embedded HTTP server based on blocking I/O components described above. HttpProcessor httpProcessor = <...> SocketConfig socketConfig = SocketConfig.custom() .setSoTimeout(15000) .setTcpNoDelay(true) .build(); final HttpServer server = ServerBootstrap.bootstrap() .setListenerPort(8080) .setHttpProcessor(httpProcessor) .setSocketConfig(socketConfig) .setExceptionLogger(new StdErrorExceptionLogger()) .registerHandler("*", requestHandler) .create(); server.start(); server.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(5, TimeUnit.SECONDS); } }); ]]>
httpcomponents-core-4.4.4/src/docbkx/advanced.xml0100644 0000000 0000000 00000040770 12613456012 020625 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.4.4/src/docbkx/fundamentals.xml0100644 0000000 0000000 00000103415 12613456012 021535 0ustar000000000 0000000 Fundamentals
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.
Repeatable entities An entity can be repeatable, meaning its content can be read 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. Please note that some non-streaming (self-contained) entities may be unable to represent their content as a java.io.InputStream efficiently. It is legal for such entities to implement HttpEntity#writeTo(OutputStream) method only and to throw UnsupportedOperationException from HttpEntity#getContent() method. 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. 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.
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 execution context Originally HTTP has been designed as a stateless, response-request oriented protocol. However, real world applications often need to be able to persist state information through several logically related request-response exchanges. In order to enable applications to maintain a processing state HttpCpre allows HTTP messages to be executed within a particular execution context, referred to as HTTP context. Multiple logically related messages can participate in a logical session if the same context is reused between consecutive requests. HTTP context functions similarly to a java.util.Map<String, Object>. It is simply a collection of logically related named values. Please nore HttpContext can contain arbitrary objects and therefore may be unsafe to share between multiple threads. Care must be taken to ensure that HttpContext instances can be accessed by one thread at a time.
Context sharing 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.
httpcomponents-core-4.4.4/src/docbkx/index.xml0100644 0000000 0000000 00000005673 12613456012 020172 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.4.4/src/docbkx/resources/0040755 0000000 0000000 00000000000 12613456013 020344 5ustar000000000 0000000 httpcomponents-core-4.4.4/src/docbkx/resources/css/0040755 0000000 0000000 00000000000 12613456013 021134 5ustar000000000 0000000 httpcomponents-core-4.4.4/src/docbkx/resources/css/hc-tutorial.css0100644 0000000 0000000 00000012227 12613456013 024102 0ustar000000000 0000000 /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation. For more information on the Apache Software Foundation, please see . ==================================================================== Based on the CSS file for the Spring Reference Documentation. */ body { text-align: justify; margin-right: 2em; margin-left: 2em; } a:active { color: #003399; } a:visited { color: #888888; } p { font-family: Verdana, Arial, sans-serif; } dt { font-family: Verdana, Arial, sans-serif; font-size: 12px; } p, dl, dt, dd, blockquote { color: #000000; margin-bottom: 3px; margin-top: 3px; padding-top: 0px; } ol, ul, p { margin-top: 6px; margin-bottom: 6px; } p, blockquote { font-size: 90%; } p.releaseinfo { font-size: 100%; font-weight: bold; font-family: Verdana, Arial, helvetica, sans-serif; padding-top: 10px; } p.pubdate { font-size: 120%; font-weight: bold; font-family: Verdana, Arial, helvetica, sans-serif; } td { font-size: 80%; } td, th, span { color: #000000; } blockquote { margin-right: 0px; } h1, h2, h3, h4, h6, H6 { color: #000000; font-weight: 500; margin-top: 0px; padding-top: 14px; font-family: Verdana, Arial, helvetica, sans-serif; margin-bottom: 0px; } h2.title { font-weight: 800; margin-bottom: 8px; } h2.subtitle { font-weight: 800; margin-bottom: 20px; } .firstname, .surname { font-size: 12px; font-family: Verdana, Arial, helvetica, sans-serif; } table { border-collapse: collapse; border-spacing: 0; border: 1px black; empty-cells: hide; margin: 10px 0px 30px 50px; width: 90%; } div.table { margin: 30px 0px 30px 0px; border: 1px dashed gray; padding: 10px; } div .table-contents table { border: 1px solid black; } div.table > p.title { padding-left: 10px; } td { padding: 4pt; font-family: Verdana, Arial, helvetica, sans-serif; } div.warning TD { text-align: justify; } h1 { font-size: 150%; } h2 { font-size: 110%; } h3 { font-size: 100%; font-weight: bold; } h4 { font-size: 90%; font-weight: bold; } h5 { font-size: 90%; font-style: italic; } h6 { font-size: 100%; font-style: italic; } tt { font-size: 110%; font-family: "Courier New", Courier, monospace; color: #000000; } .navheader, .navfooter { border: none; } pre { font-size: 110%; padding: 5px; border-style: solid; border-width: 1px; border-color: #CCCCCC; background-color: #f3f5e9; } ul, ol, li { list-style: disc; } hr { width: 100%; height: 1px; background-color: #CCCCCC; border-width: 0px; padding: 0px; } .variablelist { padding-top: 10px; padding-bottom: 10px; margin: 0; } .term { font-weight: bold; } .mediaobject { padding-top: 30px; padding-bottom: 30px; } .legalnotice { font-family: Verdana, Arial, helvetica, sans-serif; font-size: 12px; font-style: italic; } .sidebar { float: right; margin: 10px 0px 10px 30px; padding: 10px 20px 20px 20px; width: 33%; border: 1px solid black; background-color: #F4F4F4; font-size: 14px; } .property { font-family: "Courier New", Courier, monospace; } a code { font-family: Verdana, Arial, monospace; font-size: 12px; } td code { font-size: 110%; } div.note * td, div.tip * td, div.warning * td, div.calloutlist * td { text-align: justify; font-size: 100%; } .programlisting .interfacename, .programlisting .literal, .programlisting .classname { font-size: 95%; } .title .interfacename, .title .literal, .title .classname { font-size: 130%; } .programlisting * .lineannotation, .programlisting * .lineannotation * { color: blue; } .bannerLeft, .bannerRight { font-size: xx-large; font-weight: bold; } .bannerLeft img, .bannerRight img { margin: 0px; } .bannerLeft img { float:left; text-shadow: #7CFC00; } .bannerRight img { float:right; text-shadow: #7CFC00; } .banner { padding: 0px; } .banner img { border: none; } .clear { clear:both; visibility: hidden; } httpcomponents-core-4.4.4/src/docbkx/resources/xsl/0040755 0000000 0000000 00000000000 12613456013 021152 5ustar000000000 0000000 httpcomponents-core-4.4.4/src/docbkx/resources/xsl/html_chunk.xsl0100644 0000000 0000000 00000011722 12613456013 024036 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